首页 > 解决方案 > 在 ::operator = 中从我自己调用类构造函数

问题描述

我正在class::operator=为我的 c++ 代码编写代码,并尝试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]
}

但是,我找不到正确重写指针的方法,例如 using *this = *abcde,或调用类本身的构造函数,例如底部两行。我该怎么办?

标签: c++constructoroperator-keyword

解决方案


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

std::swap(*this, other);

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

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


推荐阅读