在::operator=中从我自己调用类构造函数



我正在为我的c++代码编写class::operator=,并试图在这个代码片段中克隆类参数right

myClass & myClass::operator =(const myClass &right){
myClass *abcde = new myClass(right); 
myClass coolvar(right); //this and the previous line work, but don't update the class
*this = *abcde; //uses = operator, so infinitely loops
myClass *this = new myClass(right); // doesn't work [expected unqualified-id]
myClass this(right); // doesn't work [expected unqualified-id]
}

然而,我找不到正确重写指针的方法,比如使用*this = *abcde,或者像下面两行那样调用类本身的构造函数。我该怎么做?

我不认为你真的想构造一个对象。正确的方法是提供用户定义的std::swap,并在新构建的对象上使用:

std::swap(*this, other);

请参阅:复制和交换习语是什么?

如果您想复制对象中的数据,也可以尝试std::memcy。

最新更新