简体   繁体   English

重载的赋值运算符未得到调用

[英]Overloaded assignment operator is not getting called

I have written a overloaded assignment operator of class perform copying all the variable values. 我写了一个重载的类赋值运算符, perform复制所有变量值的操作。 For ex :in Exp.cpp 例如:在Exp.cpp中

class perform
{
    LOG *ptr;
int a;
//constructor
//destructor
perform operator=(const perform & rhs){

   ptr = rhs.ptr; a=rhs.s;
return * this;}
};

In another class output , I have declared a pointer for abc . 在另一个类output ,我声明了abc的指针。

perform * ptr = StatCol::CreateCol(frm);
abc = ptr; //this line should invoke assignment overloaded.
           //but in my case it's not invoked.

Assuming abc is a Perform object, you need to dereference the pointer you are assigning: 假设abc是Perform对象,则需要取消引用要分配的指针:

abc = * ptr;

If abc itself is a pointer, then you can't do what you are asking - you can't overload assignment where the LHS is a pointer. 如果abc本身是一个指针,那么您将无法执行所要求的操作-如果LHS是指针,则无法重载分配。 You would have to dereference both pointers: 您将必须取消引用两个指针:

* abc = * ptr;

Also, it is safer to return via reference thus avoiding a copy constructor being invoked. 同样,通过引用返回更安全,从而避免了调用复制构造函数。

    const perform& operator=(const perform & rhs){

     if (this != &rhs)
     {
       ptr = rhs.ptr; a=rhs.s;
     }
     return * this;
   }
Custom assignment operator works only with user defined types so do like this:

perform p1,p2; 
p1 = p2;
perform *p = &p2;
p1 = *p;  


You can't override assignment of built in types(int , char etc.).

perform *p1,*p2; 
p1 = p2;

It simply copies the address of p2 to p1.

In the sample code you are assigning pointers, so there is no chance you could ever call the assignment operator without dereferencing the pointer. 在示例代码中,您正在分配指针,因此在不取消引用指针的情况下,您不可能调用分配操作符。

And using this design, the risk of doing shallow copy is huge. 使用这种设计,进行浅拷贝的风险很大。 In addition the C++ assignment operator signature is: 'perform & operator = ( ... )' as stated in the standard. 另外,C ++赋值运算符签名为:'perform&operator =(...)',如标准中所述。 It must return a reference to the same object in order for the compiler to consider it as you expect. 它必须返回对同一对象的引用,以便编译器按照您的期望进行考虑。

more about assignment operator... . 有关赋值运算符的更多信息...。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM