Change 'this' pointer of an object to point different object

后端 未结 6 1379
花落未央
花落未央 2021-02-07 08:01
class C{
   //methods and properties
}

void C::some_method(C* b){
    delete this;
    this = b;     
}

This gives me follwing error when compiling:

6条回答
  •  甜味超标
    2021-02-07 08:50

    You can't assign a different value to this as it point to the object itself, and this haven't any sense. You could instantiate a new object and use its implicit this pointer instead.

    Moreover, if you try to make a copy of object, you can overwrite operator=

    class Foo
    {
      public:
        [...]
        Foo& operator=(const Foo& foo);
    }
    
    int main()
    {
     Foo foo;
     foobar = foo; //invoke operator= overwrited method
    }
    


提交回复
热议问题