为了账号安全,请及时绑定邮箱和手机立即绑定

您好,想咨询一下关于C++友元函数的问题?

您好,想咨询一下关于C++友元函数的问题?

慕的地10843 2021-06-30 17:07:48
#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;
}



查看完整回答
反对 回复 2021-07-04
  • 2 回答
  • 0 关注
  • 365 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信