构造函数问题

[复制链接]
 楼主| 秋天落叶 发表于 2012-5-7 19:02 | 显示全部楼层 |阅读模式
#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,
但是实际上运行的时候不行,为什么呢?
不会又是编译器的问题吧
yybj 发表于 2012-5-7 19:18 | 显示全部楼层
你重载的 + 是两个Complex类型的相加运算。
  c3=c1+5;
  cout <<"c1+5="<<c3<<endl;
  c3=6+c2;
  cout <<"6+c2="<<c3<<endl;
这两个地方却是 Complex与整型的相加算,你还要再重载一个Complex与整型的 +
您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:落叶很美

138

主题

3044

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部