为何下面的程序类型转换函数和转换构造函数同时出现却没有出现二义性
#include<iostream.h>
class Complex
{
public:
Complex() //默认构造函数
{
real = 0;
imag = 0;
}
Complex(double r, double i) //初始化构造函数
{
real = r;
imag = i;
}
Complex(double d) //转换构造函数
{
real = d;
imag = 0;
}
operator double() //类型转换函数
{
return real;
}
friend Complex operator+ (Complex &c1, Complex &c2);
void display();
private:
double real;
double imag;
};
Complex operator+ (Complex &c1, Complex &c2)
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
void Complex :: display()
{
cout << "(" << real << ", " << imag << ")" << endl;
}
int main()
{
Complex c1(3, 4), c4;
c4 = 5.0 + c1;
c4.display();
return 0;
}
[解决办法]
重载运算符这么写就有二义性了。
Complex operator+ (Complex const&c1, Complex const&c2)
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}