#include <iostream>
using namespace std;
class Complex
{
public:
Complex(int a=0,int b=0)
{
this->a = a;
this->b = b;
}
friend Complex operator+(Complex c1, Complex c2);
friend ostream& operator<<(ostream &out, Complex &c1);
void printfComplex()
{
cout << this->a << " " << this->b << endl;
}
private:
int a;
int b;
};
Complex operator+(Complex c1, Complex c2)
{
Complex temp;
temp.a = c1.a + c2.a;
temp.b = c1.b + c2.b;
return temp;
}
/* 不应该返回空,不利于链式编程
void operator<<(ostream &out, Complex &c1)
{
cout << c1.a << " " << c1.b << " " << c1.a + c1.b << endl;
}
*/
ostream& operator<<(ostream &out, Complex &c1)
{
cout << c1.a << " " << c1.b << " " << c1.a + c1.b << endl;
return out;
}
int main()
{
Complex c1(1, 2), c2(3,4);
Complex c3;
c3 = c1 + c2;
c3.printfComplex();
//重写<<操作符,由于无法获取ostream的源码,所以只能使用成员函数法重写,此时使用友元函数获取类中的private变量
cout << c3;
system("pause");
return 0;
}