Operator overload: normal MSVS, but crashing in g ++

I have code that compiles without errors in Visual Studio 2010. But g ++ puts an error

CComplex.cpp: In member function 'Complex Complex::operator+(Complex&)': CComplex.cpp:22: error: no matching function for call to 'Complex::Complex(Complex)' CComplex.cpp:15: note: candidates are: Complex::Complex(Complex&) make: *** [CComplex.o] Error 1 

Please tell me what the problem is with my code.

complex.h

 class Complex { public: Complex(); Complex(double _Re, double _Im); Complex(Complex& c); Complex operator+(Complex& num); inline double& fRe(void){return Re;} inline double& fIm(void){return Im;} protected: double Re; double Im; } 

Complex.cpp

 Complex::Complex(){ Re = 0.0; Im = 0.0; } Complex::Complex(double re, double im){ Re = re; Im = im; } Complex::Complex(Complex& complex){ *this = complex; } Complex Complex::operator+(Complex& num){ return Complex(Re + num.fRe(), Im + num.fIm()); }; 
0
source share
1 answer
 Complex Complex::operator+(Complex& num){ return Complex(Re + num.fRe(), Im + num.fIm()); }; 

In the callback, copies c-tor for a temporary object that cannot be bound to lvalue-reference. Use

 Complex(const Complex& c); 

And for operator + use also

Complex operator + (const Complex& c)

or

Complex operator + (Complex c)

For the first cases, the functions fRe and fIm must be constant functions, or you must make an explicit copy of the passed object.

It can be compiled in MSVC and not compiled in g ++, because MSVC does not mistakenly check for a valid copy constructor when optimizing the return value .

+6
source

Source: https://habr.com/ru/post/1432087/


All Articles