overload of operator: ok MSVS but fails in g++

ⅰ亾dé卋堺 提交于 2019-12-25 11:27:35

问题


I have code which compiles without error in Visual Studio 2010. But g++ puts 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's the problem 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());
};

回答1:


Complex Complex::operator+(Complex& num){
    return Complex(Re + num.fRe(), Im + num.fIm());
};

In return calls copy c-tor for temporary-object, that cannot be binded to lvalue-reference. Use

Complex(const Complex& c);

And for operator + use also

Complex operator + (const Complex& c)

or

Complex operator + (Complex c)

For first case functions fRe and fIm shall be constant functions, or you should do explicit copy of passed object.

It can be compiled in MSVC and not compiled in g++, because MSVC wrongly does not check for an existence of acceptable copy constructor when performing Return Value Optimization.



来源:https://stackoverflow.com/questions/12001054/overload-of-operator-ok-msvs-but-fails-in-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!