樱花雨2377
2015-10-20 10:48
采纳率: 66.7%
浏览 2.0k

c++运算符重载问题,友元函数

#include
#include
using namespace std;

class Complex
{

public:
    Complex(double newx=0.0, double newy=0.0 );
    //Complex();
    Complex(Complex &c);
    double getx() const;
    double gety() const;
    Complex Add(const Complex &another);
    void Output();
    friend istream & operator>>(istream &in, const Complex &c);
    friend ostream & operator<<(ostream &out, const Complex &c);

    Complex operator+(const Complex &c2)const;



    ~Complex(){};
private:
    double x,y;

};

Complex::Complex(double newx, double newy)
{
x=newx;
y=newy;
}
/*Complex::Complex()
{
x=0;
y=0;
}
*/
Complex::Complex(Complex &c)
{
x=c.x;
y=c.y;
}
double Complex::getx()const
{
return x;
}
double Complex::gety()const
{
return y;
}
Complex Complex::Add(const Complex &another)
{
Complex r;
r.x=x+another.getx();
r.y=y+another.gety();
return r;
}
void Complex::Output()
{
cout< if(y>=0)
cout<<"+";
cout<<y<<"i"<<endl;
}

Complex Complex::operator+(const Complex &c2)const
{
return Complex(x+c2.x,y+c2.y);
}

istream & operator>>(istream &in, const Complex &c)
{
// in>>"(">>c.x>>","< in>>c.x;
in>>c.y;
return in;
}

ostream & operator<<(ostream &out, const Complex &c)
{
out<<"("<<c.x<<","<<c.y<<")";
return out;
}

int main(int argc,char&agrv[])
{

Complex z1(3,5),z2(4.5,2.3),z3(2,3);
Complex z4;
Complex z5(z1);
z5.Output();
cin>>z1;
cin>>z2;
z4=z1.Add(z2);
z4.Output();
z3 = z1+z2;
z3.Output();
return 0;

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题