操作后通过运算符分配对象

Assigning object after operation via operator

本文关键字:分配 对象 运算符 操作      更新时间:2023-10-16

我想添加两个类的内容并将它们保存在另一个类中。我已经创建了构造函数、参数化构造函数、析构函数和重载=参数。它对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&( 作为其参数,无法绑定到addition返回的临时对象。

要解决此问题,您应该将参数类型更改为引用 const(即const Demo&(,可以绑定到临时的并且是约定俗成的。

顺便说一句:任务的目标和来源似乎是相反的。我想它应该实现为

Demo& operator= (const Demo& obj) {
setData(obj.getData());
return *this;
}

并将getData声明为const成员函数。