开发者社区> 问答> 正文

c++用成员函数和友元函数实现复数的加减操作,产生了二义性,麻烦各位大哥大姐解答一下,感激不尽

我想在一个程序中用友元函数和类的成员函数实现复数的加减操作,
类中这样定义:
screenshot

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;
}

展开
收起
a123456678 2016-03-06 18:04:27 2755 0
1 条回答
写回答
取消 提交回答
  • c3=c1+c2;//对象+对象
    用成员函数 Complex operator+ (const Complex &c2)const;

    c3=4+c2; //数+对象
    用友元函数
    friend Complex operator+ (double r, const Complex &c2);

    2019-07-17 18:55:00
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载