用友元函数重载加号,进行复数和实数的加法时加号两端的操作数怎么还是不能互换?以下面程序为例:#include using std::cout;using std::endl;class Complex{friend Complex operator +(double d,const Complex &c);public:Complex(){dReal=0;dImag=0;}Complex(double r,double i){dReal=r; dImag=i;}void print()const;private:double dReal;double dImag;};//友元函数实现Complex operator +(double d,const Complex &c) {return Complex(d+c.dReal,c.dImag);}void Complex::print()const{cout
问题描述:
用友元函数重载加号,进行复数和实数的加法时加号两端的操作数怎么还是不能互换?以下面程序为例:
#include
using std::cout;
using std::endl;
class Complex
{
friend Complex operator +(double d,const Complex &c);
public:
Complex(){dReal=0;dImag=0;}
Complex(double r,double i){dReal=r; dImag=i;}
void print()const;
private:
double dReal;
double dImag;
};
//友元函数实现
Complex operator +(double d,const Complex &c)
{
return Complex(d+c.dReal,c.dImag);
}
void Complex::print()const
{
cout
答
大哥...
你只定义了double + complex的,没定义complex+double的啊
c0=c1+d1,电脑想第一个应该是double的,咦味道不对,怎么是Complex的,报错
再加一个友元函数
类里面声明
friend Complex operator +(const Complex &c,double d);
类外定义
Complex operator +(const Complex &c,double d)
{
return Complex(d+c.dReal,c.dImag);
}
void Complex::print()const
{
cout}
就OK了