【发布时间】:2019-10-04 01:33:03
【问题描述】:
我试图在我的赋值运算符重载中调用我的复制构造函数。我将复制构造函数的结果分配给名为 temp 的指针,然后将 this 指针设置为等于 temp。这个结果给了我错误:左值需要作为赋值的左操作数。我认为这是指向我的对象的指针。为什么将指针重新分配给不同的对象会出现问题?
在传递的情况下,我尊重 this(*this) 并将其设置为等于 temp。对我来说,这意味着我说实际对象等于指针。我是不是误解了这个意思?
通过案例:
Foo *temp = new Foo(other); //invokes copy constructor
*this = temp;
失败案例:
Foo *temp = new Foo(other); //invokes copy constructor
this = temp;
完整源代码:
TreeNode::TreeNode(TreeNode *other) {
this->leftChild = other->leftChild;
this->rightChild = other->rightChild;
this->data = other->data;
}
TreeNode& TreeNode::operator=(TreeNode *other) {
if(this != other) {
TreeNode *temp = new TreeNode(other);
this = temp;
}
return *this;
}
【问题讨论】:
-
Proper 复制构造函数和复制赋值运算符不将指针作为输入,而是采用引用。而
this是一个const指针,不能重新赋值 -
对于
TreeNode,您根本不需要编写复制构造函数和赋值运算符。编译器生成的就足够了。
标签: c++ oop constructor operator-overloading