关于运算符(一个小程序有个错,为什么,答案合适就揭贴!!)
class complex
{
double _x,_y;
public:
complex(double x=0,double y=0):_x(x),_y(y){}
complex(double x):_x(x),_y(0){} //定义了一个构造函数,为了转换double型的
complex& operator=(const complex &);
complex& operator+(const complex &);
void dis()
{
cout<<_x<<"_"<<_y<<endl;
}
};
complex& complex::operator=(const complex &rhs)
{
_x=rhs._x;
_y=rhs._y;
return *this;
}
complex& complex::operator+(const complex &rhs)
{
_x+=rhs._x;
_y+=rhs._y;
return *this;
}
int main()
{
complex a(1,1),b(2,2),c(0,0);
a.dis();b.dis();c.dis();
c=a+b; c.dis();
c=a+3.9; c.dis(); //仅有的一个错,但是书上说可以自动转换
//的 complex(3.9)
//因为有个构造函数,so可以这样的
return 0;
}
/*error c2679: binary + : no operator defined which takes a right-hand operand of type const double (or there is no acceptable conversion)
error executing cl.exe.*/
推荐阅读
> complex(double x=0,double y=0):_x(x),_y(y){}
> complex(double x):_x(x),_y(0){}
您不觉得这两个函数是会造成二义性的吗?
如果是complex d(3.5),让编译器调哪个好呢?
解决的方案就是把第二构造函数去掉,第一个的功能已经把第二个涵盖了。
对,同意,看看重载的函数的问题就知道了,例如
fun(int i)
fun(int i = 0;int j)
fun(int i = 0;int j = 1;int k)
该调用哪个呢?
complex(double x=0,double y=0):_x(x),_y(y){}
这个函数就更有趣了,你写一个参数是它,你写两个参数还是它
complex(double x):_x(x),_y(0){} 这个根本没有用
lifanxi(byron) 说的非常对。
只要这样:
#include <iostream>
using namespace std;
class complex
{
double _x,_y;
public:
complex(double x=0,double y=0):_x(x),_y(y){}
//此处注释掉即可 complex(double x):_x(x),_y(0){}
complex& operator=(const complex &);
complex& operator+(const complex &);
void dis()
{
cout<<_x<<"_"<<_y<<endl;
}
};
complex& complex::operator=(const complex &rhs)
{
_x=rhs._x;
_y=rhs._y;
return *this;
}
complex& complex::operator+(const complex &rhs)
{
_x+=rhs._x;
_y+=rhs._y;
return *this;
}
int main()
{
complex a(1,1),b(2,2),c(0,0);
a.dis();b.dis();c.dis();
c=a+b; c.dis();
c=a+3.9; c.dis();
return 0;
}
我觉得重载“+”的函数不怎么好,如果是楼主像那样:
complex& complex::operator+(const complex &rhs)
{
_x+=rhs._x;
_y+=rhs._y;
return *this;
}
回使的当前对象的数据成员发生改变。应该:
complex& complex::operator+(const complex &rhs)
{ complex temp;
temp._x=_x+rhs._x;
temp._y=_y+rhs._y;
return temp;
}


讨论区