c++ - 通过运算符在操作后分配对象

标签 c++ operator-overloading assignment-operator

我想添加两个类的内容并将它们保存在另一个类中。我创建了构造函数、参数化构造函数、析构函数和重载的 = 参数。它对 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/

相关文章:

c++ - 如何设置来自DeviceCapability的纸质表单?

c++ - 运算符重载并出现友元函数错误

c++ - 将空 vector 传递给对象的 "correct"方法是什么?

c++ - 为什么 Visual Studio 不进入我的赋值运算符?

c++ - 将 char 设置为 '\0' 会泄漏内存吗?

c++ - SIGSEGV : Program doesn't execute sequentially

c++ - GCC 和 Clang 代码性能的巨大差异

C++增量++运算符重载

c++ - 使用重载运算符 () 在 C++ 中复制构造函数

c++ - Big 3 - 赋值运算符