【发布时间】:2018-02-04 17:14:20
【问题描述】:
我想添加两个类的内容并将它们保存在另一个类中。我创建了构造函数、参数化构造函数、析构函数和重载= 参数。它对Demo b = a; 工作正常,但是当我尝试保存a.addition(b) 给出的对象时,出现错误no viable overloaded '='。我的概念是为什么对象没有被复制到新创建的对象中?
课堂演示
class Demo
{
int* ptr;
public:
Demo(int data = 0) {
this->ptr = new int(data);
}
~Demo(void) {
delete this->ptr;
}
// Copy controctor
Demo(Demo &x) {
ptr = new int;
*ptr = *(x.ptr);
}
void setData(int data) {
*(this->ptr) = data;
}
int getData() {
return *(this->ptr);
}
Demo operator = (Demo& obj) {
Demo result;
obj.setData(this->getData());
return result;
}
Demo addition(Demo& d) {
Demo result;
cout << "result: " << &result << endl;
int a = this->getData() + d.getData();
result.setData(a);
return result;
}
};
主要
int main(void)
{
Demo a(10);
Demo b = a;
Demo c;
c = a.addition(b); // error here
return 0;
}
【问题讨论】:
-
你的赋值运算符很奇怪。它改变了 rhs 而不是 lhs。如果我写
a = b我不希望 b 被修改。 -
@StoryTeller 你是对的。那是错误的。
标签: c++ operator-overloading assignment-operator