| 发表于:2008-01-22 14:39:04 楼主 |
源程序如下: #include <iostream.h> class complex { friend complex operator+(const complex &x,const complex &y) //重载为类的友元函数 { cout < <"begin from class complex" < <endl; return complex(x.real+y.real,x.image+y.image); } public: int real; int image; public: complex() { } complex(int r,int i):real(r),image(i) //construct function {} void print(void)const { cout < <"real=" < <real < <" image=" < <image < <endl; } ~complex() {} }; class a { friend complex operator+(complex &x,complex &y) //重载为类的友元函数 { cout < <"begin from class a" < <endl; return complex(x.real+y.real,x.image+y.image); } }; void main() { complex c1(2,3),c2(4,5); complex z; z=c1+c2; z.print(); } 运行结果: begin from class a real=6 image=8 press any key to continue 问题:1、两个运算符重载函数,其中class a类中的重载函数的形参不是const类型,而complex类中的形参是const类型。在执行命令z=c1+c2后,为什么是调用的恰好是class a中的重载函数而非complex中的呢? 2、如果把class a中重载函数的形参也改为和const类型,即和complex完全一样,执行命令z=c1+c2后却调用的是complex的重载函数,这又是为什么呢? 谢谢! |
|
|
|
|