我想在一个程序中用友元函数和类的成员函数实现复数的加减操作,
类中这样定义:
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;
}