[英]Overloaded assignment operator is not getting called
我寫了一個重載的類賦值運算符, perform
復制所有變量值的操作。 例如:在Exp.cpp中
class perform
{
LOG *ptr;
int a;
//constructor
//destructor
perform operator=(const perform & rhs){
ptr = rhs.ptr; a=rhs.s;
return * this;}
};
在另一個類output
,我聲明了abc
的指針。
perform * ptr = StatCol::CreateCol(frm);
abc = ptr; //this line should invoke assignment overloaded.
//but in my case it's not invoked.
假設abc是Perform對象,則需要取消引用要分配的指針:
abc = * ptr;
如果abc本身是一個指針,那么您將無法執行所要求的操作-如果LHS是指針,則無法重載分配。 您將必須取消引用兩個指針:
* abc = * ptr;
同樣,通過引用返回更安全,從而避免了調用復制構造函數。
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.
在示例代碼中,您正在分配指針,因此在不取消引用指針的情況下,您不可能調用分配操作符。
使用這種設計,進行淺拷貝的風險很大。 另外,C ++賦值運算符簽名為:'perform&operator =(...)',如標准中所述。 它必須返回對同一對象的引用,以便編譯器按照您的期望進行考慮。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.