#include <iostream>
using namespace std;
class Complex
{
public:
Complex()
{
}
Complex(int a,int b)
{
this->m_a = a;
this->m_b = b;
}
void printCom()
{
cout<<m_a<<"+"<<m_b<<"i"<<endl;
}
//成员函数方法实现+
Complex operator+(Complex &obj)
{
Complex tmp(this->m_a+obj.m_a,this->m_b+obj.m_b);
return tmp;
}
//成员函数实现前置--
Complex& operator--()
{
this->m_a--;
this->m_b--;
return *this;
}
//成员函数实现后置--
Complex operator--(int)
{
Complex tmp = *this;
this->m_a--;
this->m_b--;
return tmp;
}
private:
int m_a;
int m_b;
friend Complex operator-(Complex &obj1,Complex &obj2);
friend Complex& operator++(Complex &obj1);
friend Complex operator++(Complex &obj1,int);
friend ostream& operator<<(ostream &out,Complex &obj1);
protected:
private:
};
//全局函数方法实现+
Complex operator-(Complex &obj1,Complex &obj2)
{
Complex tmp (obj1.m_a-obj2.m_a,obj1.m_b-obj2.m_b);
return tmp;
}
//全局函数实现前置++
Complex& operator++(Complex &obj1)
{
obj1.m_a++;
obj1.m_b++;
return obj1;
}
//全局函数实现后置++
Complex operator++(Complex &obj1,int)
{
Complex tmp = obj1;
obj1.m_a++;
obj1.m_b++;
return tmp;
}
//友元函数的真正应用场景
//全局函数实现<< 只能使用全局函数的形式 为什么? 我们没法再ostream类中添加重载<<的成员函数
//链式编程 返回值为ostream的引用
ostream& operator<<(ostream &out,Complex &obj1)
{
out<<obj1.m_a<<"+"<<obj1.m_b<<"i";
return out;
}
int main()
{
Complex m1(1,2);
Complex m2(3,4);
/*Complex m3;
m3 = m1 + m2 ;
m3.printCom();
m3 = m2 - m1;
m3.printCom();
++m1;
m1.printCom();
--m1;
m1.printCom();
m1++;
m1.printCom();
m1--;
m1.printCom();
*/
cout<<m1<<endl;
system("pause");
return 0;
}