我想添加两个类的内容并将它们保存在另一个类中。我创建了构造函数、参数化构造函数、析构函数和重载的 =
参数。它对 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;
}
最佳答案
operator=
以非常量(即Demo&
)的引用作为参数,不能绑定(bind)到addition 返回的临时对象
。
要解决这个问题,您应该将参数类型更改为对 const 的引用(即 const Demo&
),它可以绑定(bind)到临时的并且是常规的。
顺便说一句:赋值的目标和来源似乎是相反的。我想它应该实现为
Demo& operator= (const Demo& obj) {
setData(obj.getData());
return *this;
}
并将getData
声明为const
成员函数。
关于c++ - 通过运算符在操作后分配对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45901971/