C++之重载流插入运算符

#include <iostream>


using namespace std;


class Complex 
{
public:
Complex()
{
real=0;
imag=0;
}
Complex(double r,double i):real(r),imag(i){}
Complex operator +(Complex &);
friend ostream & operator <<(ostream &,Complex &);

private:
double real;
double imag;
};


Complex Complex::operator +(Complex &c2)
{
return Complex(real+c2.real,imag+c2.imag);
}


ostream & operator <<(ostream & output,Complex & c)
{
output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;
return output;
}


int main()
{
Complex c1(1,0),c2(0,1),c3;
c3=c1+c2;
cout<<"c1+c2=";
cout<<c3;

return 0;
}

猜你喜欢

转载自blog.csdn.net/wrc_nb/article/details/80618712