简体   繁体   English

运算符的重载:好的MSVS,但在g ++中失败

[英]overload of operator: ok MSVS but fails in g++

I have code which compiles without error in Visual Studio 2010. But g++ puts error 我有可以在Visual Studio 2010中正确编译的代码。但是g ++会出错

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.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());
};
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. 在返回调用中,复制临时对象的c-tor,该临时对象不能绑定到左值引用。 Use 采用

Complex(const Complex& c);

And for operator + use also 对于operator +也可以使用

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. 对于第一种情况,函数fRefIm应该是常量函数,或者您应该对传递的对象进行显式复制。

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 . 可以在MSVC中编译它,而不能在g ++中编译它,因为在执行Return Value Optimization时, MSVC错误地不检查是否存在可接受的副本构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM