#include<iostream>using namespace std;class complex{ private:int real,imag;public:complex(int a=0,int b=0);void set();complex operator+(complex &); //为什么这样就是错误的呢?complex operator-(complex &);complex operator*(complex &);complex operator/(complex &);void show();~complex(){cout<<"析构函数";}};complex::complex(int a,int b){real=a;imag=b;}void complex::set(){ cout<<"please input the factors:"<<endl;cin>>real>>imag;}complex complex::operator +(complex &a){ complex c;c.real=a.real+real;c.imag=a.imag+imag;return c;}complex complex::operator -(complex &b){ complex c;c.real=real-b.real;c.imag=imag-b.imag;return c;}complex complex::operator *(complex &b){ complex c;c.real=real*b.real-imag*b.imag;c.imag=real*b.imag+imag*b.real;return c;}complex complex::operator /(complex &b){ complex c;int n=b.real*b.real+b.imag*b.imag;c.real=(real*b.real+imag*b.imag)/n;c.imag=(imag*b.real-real*b.imag)/n;return c;}void complex::show(){if(imag>0)cout<<real<<"+"<<imag<<"j"<<endl;else if(imag==0)cout<<real<<endl;else cout<<real<<imag<<"j"<<endl;}void main(){complex m(1,3),n(6,3),t;m.set();n.set();t=m-n;m.show();n.show();t.show();}以上为一复数运算符重载的函数。运行正确。我的问题是,为什么我把这里面的运算符重载改为友元函数会是错误的,提示内部编译器有误。请高手指点
2 回答
临摹微笑
TA贡献1982条经验 获得超2个赞
友元函数就需要两个参数了:
friend complex operator+(complex &a, complex &b); //为什么这样就是错误的呢?
complex operator +(complex &a, complex &b)
{
complex c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return c;
}
- 2 回答
- 0 关注
- 365 浏览
添加回答
举报
0/150
提交
取消