本文介绍了运算符的重载:好的MSVS,但在g ++中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可以在Visual Studio 2010中正确编译的代码.但是g ++会出错

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

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());
};

在返回调用中,复制临时对象的c-tor,该临时对象不能绑定到左值引用.使用

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

Complex(const Complex& c);

对于operator +,也可以使用

Complex operator + (const Complex& c)

Complex operator + (Complex c)

对于第一种情况,函数fRefIm应该是常量函数,或者您应该对传递的对象进行显式复制.

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

它可以在MSVC中进行编译,而不能在g ++中进行编译,因为 MSVC错误地不会检查是否存在可接受的副本构造函数执行返回值优化时.

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.

这篇关于运算符的重载:好的MSVS,但在g ++中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:43