我想在一個程序中用友元函數和類的成員函數實現復數的加減操作,
類中這樣定義:
main函數中用這幾句調用的話存在二義性:
c3=c1+c2;這一句就不知道到底該調用成員函數還是調用友元函數,但是重載的話只有參數類型和參數個數不同,就應該沒問題的,這裡該怎麼解決呢?
麻煩各位大哥大姐了;下面是程序的代碼,
#include
class Complex
{
public:
Complex(double r=0.0,double i=0.0):real(r),imag(i){}
Complex operator+ (const Complex &c2)const;
Complex operator- (const Complex &c2)const;
friend Complex operator+(const Complex &c1,const Complex &c2);
friend Complex operator-(const Complex &c1,const Complex &c2);
friend ostream &operator<< (ostream &out,const Complex &c);
void display()const;
private:
double real;
double imag;
} ;
Complex Complex::operator+ (const Complex &c2)const
{
return Complex(real+c2.real,imag+c2.imag);
}
Complex Complex::operator- (const Complex &c2)const
{
return Complex(real-c2.real,imag-c2.imag);
}
void Complex::display()const
{
cout<<"("<<real<<","<<imag<<")"<<endl;
}
Complex operator+(const Complex &c1,const Complex &c2)
{
return Complex(c1.real+c2.real,c1.imag+c2.imag);
}
Complex operator-(const Complex &c1,const Complex &c2)
{
return Complex(c1.real-c2.real,c1.imag-c2.imag);
}
ostream &operator<< (ostream &out,const Complex &c)
{
out<<"("<<c.real<<","<<c.imag<<")"<<endl;
return out;
}
int main()
{
Complex c1(5,4),c2(2,10),c3;
c1.display();
c2.display();
c3.display();
c3=c1+c2;
c3.display();
cout<<c3;
c3=c3-c1;
c3.display();
cout<<c3;
return 0;
}
你在函數裡寫個輸出就能看出優先級了,具體我也沒試過,無法給出正確答案