c++初学菜鸟请教高手问题,还请高手帮忙!!!感谢了
#include <iostream.h>
class Complex
{public:
Complex(){real = 0; imag = 0;};
Complex(int r, int i){real = r; imag = i;}
operator int(){return real; } //类型转换函数
friend Complex operator + (Complex c1, Complex c2); //对+的重载
Complex(int r){real = r, imag = 0; } //转换构造函数
public:
int real;
int imag;
};
Complex operator + (Complex c1, Complex c2)
{
Complex c3;
c3.real =c1.real + c2.real;
c3.imag = c1.imag + c2.imag;
return c3;
}
int main(void)
{
int c , b = 2;
Complex a(5,8);
c = a + b; //请问下是不是这个地方发生了,不知道是调用类型转换函数,或
cout < <c < <endl; //是调用转换构造函数的2义性啊??
return 0;
}
--------------------Configuration: time - Win32 Debug--------------------
Compiling...
time.cpp
F:\编程\TMP1\time.cpp(29) : error C2666: '+ ' : 2 overloads have similar conversions
Error executing cl.exe.
time.exe - 1 error(s), 0 warning(s)
请问下是不是程序发生了不知道是调用是调用转换构造函数的2义性啊??
[解决办法]
确实是那里出了问题,以前看《More Effective C++》的时候有讲过这个问题,但是时间太长
了,我忘记那里面怎么处理的了。我的想法是这样的,你可以重载一个+的函数,像这样:
friend Complex operator+( Complex c1, int r )
{
Complex c3;
c3.real = c1.real + r;
return c3;
}
这样就能解决问题了。或者还可以给类做一个缺省构造函数,可以将int类型转换为Complex类
型,如下:
Complex::Complex( int r=0 )
{
real = r;
}
这样int类型就能隐式的转化为Complex类型了。
[解决办法]
偶是新手,不知楼主下面这句行吗?int可以重载吗?
operator int(){return real; } //类型转换函数
[解决办法]
你的问题答案就是调用转换构造函数的2义性 重载+和类型转换函数和转换构造函数同时存在时就会产生..C=A+B B被看作Complex(2,O)或者A被看作5 产生歧义 解决的办法楼上都说了..