class Test { public: Test(int a = 0) { Test::a = a; } friend Test operator +(Test&,Test&); friend Test& operator ++(Test&); public: int a; }; Test operator +(Test& temp1,Test& temp2)//+运算符重载函数 { //cout<<temp1.a<<"|"<<temp2.a<<endl;//在这里可以观察传递过来的引用对象的成员分量 Test result(temp1.a+temp2.a);
return result; } Test& operator ++(Test& temp)//++运算符重载函数 { temp.a++; return temp; } int main() { Test a(100); Test c=a+a; cout<<c.a<<endl; c++; cout<<c.a<<endl; system("pause"); } 在例子中,我们对于自定义类Test来说,重载了加运算符与自动递增运算符,重载的运算符完成了同类型对象的加运算和递增运算过程重载运算符函数返回类型和形式参数也是根据需要量进行调整的,下面我们来看一下修改后的加运算符重载函数。
class Test { public: Test(int a = 0) { Test::a = a; } friend Test operator +(Test&,const int&); public: int a; }; Test operator +(Test& temp1,const int& temp2)//+运算符重载函数 { Test result(temp1.a * temp2); return result; } int main() { Test a(100); Test c = a + 10; cout<<c.a<<endl;