C++;重载运算符+;,复制构造函数的问题 我学习C++,在学习运算符重载时遇到这个问题:

C++;重载运算符+;,复制构造函数的问题 我学习C++,在学习运算符重载时遇到这个问题:,c++,operator-overloading,C++,Operator Overloading,我定义了一个复杂的类: class Complex { private: double real, imag; public: Complex() = default; Complex(double real,double imag): real(real), imag(imag) { std::cout << "Double constructor" << std::endl; } // Complex(Com

我定义了一个复杂的类:

class Complex {
private:
    double real, imag;

public:
    Complex() = default;

    Complex(double real,double imag): real(real), imag(imag) {
        std::cout << "Double constructor" << std::endl;
    }

//    Complex(Complex &other) {
//        this->real = other.real;
//        this->imag = other.imag;
//        std::cout << "Copy constructor" << std::endl;
//    }

    Complex operator+(Complex &other) {
            return Complex(real+other.real, imag+other.imag);
    }

    ~Complex() {
        std::cout << "Desctuctor called: " << real << std::endl;
    }
};
对吗


我找不到任何有用的东西,所以(或者我太笨了,看不透),非常感谢任何帮助

您的
操作符+
函数返回一个
复数
by值,因此它必须调用复制构造函数

在没有自定义构造函数的情况下,编译器会生成一个默认的复制构造函数,该构造函数工作得很好(它执行memberwise复制)

对于自定义构造函数,编译器不会生成默认的副本构造函数。但是,自定义副本构造函数有一个不寻常的类型:

Complex(Complex &other)
需要左值作为输入。它不能用于复制临时文件


编译器生成的复制构造函数取而代之的是
constcomplex&other
,它可以绑定到临时值。

您遇到了什么错误?请粘贴准确的错误消息
Complex operator+(Complex&other){
对于复制构造函数参数应为
Complex operator+(const Complex&other){
相同ῥεῖ 谢谢你指出。加上
常数实际上使事情运转起来,你能解释一下吗?
Complex(Complex &other)