#include <iostream>
using namespace std;
class Test
{
public:
int a;
int b;
public:
Test(int a=0, int b=0)
{
cout << "有参构造函数" << endl;
this->a = a;
this->b = b;
}
~Test()
{
cout << "a=" << a;
cout << "析构函数" << endl;
}
void prinT()
{
cout << "a=" << a << "b=" << b << endl;
}
Test operator+(Test &t2)//类函数实现+号重载
{
Test tmp(this->a + t2.a, this->b + t2.b);
return tmp;
}
Test& operator++()//前置++的重置
{
cout << "调用前置++" << endl;
this->a++;
this->b++;
return *this;
}
Test operator++(int)//后置++的重置,利用占位形参实现函数重载
{
cout << "调用后置++" << endl;
Test tmp = *this;
return tmp;
this->a++;
this->b++;
}
};
Test operator+(Test &t1, Test &t2)//全局函数方法实现+号重载
{
cout << "运算符重载" << endl;
Test tmp(t1.a + t2.a, t1.b + t2.b);
return tmp;
}
int main()
{
Test t1(1, 2);
Test t2(3, 4);
Test t3 = t1 + t2;
t3.prinT();
system("pause");
return 0;
}
当类成员被定义为私有的,可利用友元函数实现全局运算符重载