亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

您好,想咨詢一下關于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 關注
  • 410 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號