c++ - 在 ::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
,或调用类本身的构造函数,例如底部两行。我该怎么办?
解决方案
我不认为你真的想构造一个对象。正确的做法是提供一个用户定义std::swap
并在一个新构造的对象上使用:
std::swap(*this, other);
请参阅: 什么是复制和交换习语?
如果要复制对象中的数据,也可以尝试std::memcy。
推荐阅读
- java - 我的应用程序如何监听 android 系统音量的变化?
- sql - Oracle Query 从具有不同条件的单个表中获取两个值
- java - 具有原始值(或 Double)的Java 泛型`capture`
- c# - 访问远程服务器以进行文件 I/O
- django - Django - 无法在模板中调用函数并将该函数的值返回到同一页面
- python - 函数的返回值为 None 并且不能返回第一个键
- ms-access - 控制源 IIF 语句无效的语法错误
- go - Golang graphql模式字段无法返回数组
- javascript - 为什么使用 ` 而不是 " 用于字符串
- dart - Flutter-下拉按钮问题