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

#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();
}

以上为一复数运算符重载的函数。运行正确。

我的问题是,为什么我把这里面的运算符重载改为友元函数会是错误的,提示内部编译器有误。
请高手指点

慕的地10843
浏览 333回答 2
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;}
打开App,查看更多内容
随时随地看视频慕课网APP