#include<iostream.h>
class Complex{public:
Complex(){real=0;imag=0;} //构造函数
Complex(float r,float i){real=r;imag=i;} //带参构造函数
Complex(float r){real=r;imag=0;} //转换构造函数
friend Complex operator
+(Complex&,Complex&);
friend ostream&
operator
<<(ostream&,Complex&);
private:
float real;
float imag;
};
//对'+'重载
Complex operator
+(Complex&c1,Complex&c2)
{
return ( Complex(c1.real+c2.real,c1.imag+c2.imag) );
};
//对"<<"重载
ostream&
operator
<<(ostream&output,Complex&c)
{
output <<c.real<<"+"<<c.imag<<"i."<<endl;
return output;
};
int main()
{
Complex c1(1,2),c2(3,4),c3;
cout <<"c1="<< c1<<endl;
cout <<"c2="<< c2<<endl;
cout <<"c1+c2="<<c1+c2<<endl;
c3=c1+5;
cout <<"c1+5="<<c3<<endl;
c3=6+c2;
cout <<"6+c2="<<c3<<endl;
return
0;
}
这个程序错误提示 error C2678: binary '+' : no operator defined which takes a left-hand operand of type 'const int' (or there is no acceptable conversion)
问题是:为什么不行,按照课本上说c3=c1+5,首先寻找有没有对+重载,发现有,但是类型不对,不能调用,然后又没有对float进行中重载,因此不可能把c1转换成float类型,最后寻找有没有转换构造函数,发现有,就调用转换构造函数
Complex(5),建立一个临时的Comlex类对象,再调用operator+函数,相加赋给c3,
但是实际上运行的时候不行,为什么呢?
不会又是编译器的问题吧 |