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)//+運算符重載函數(shù) { //cout<<temp1.a<<"|"<<temp2.a<<endl;//在這里可以觀察傳遞過來的引用對象的成員分量 Test result(temp1.a+temp2.a);
return result; } Test& operator ++(Test& temp)//++運算符重載函數(shù) { 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來說,重載了加運算符與自動遞增運算符,重載的運算符完成了同類型對象的加運算和遞增運算過程重載運算符函數(shù)返回類型和形式參數(shù)也是根據(jù)需要量進(jìn)行調(diào)整的,下面我們來看一下修改后的加運算符重載函數(shù)。
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)//+運算符重載函數(shù) { Test result(temp1.a * temp2); return result; } int main() { Test a(100); Test c = a + 10; cout<<c.a<<endl;