3 回答
TA貢獻1796條經驗 獲得超4個贊
#include <iostream>
using namespace std;
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來說,重載了加運算符與自動遞增運算符,重載的運算符完成了同類型對象的加運算和遞增運算過程。
TA貢獻1844條經驗 獲得超8個贊
應該這樣可以吧,
int operator + (const T & t1,T & t2) //T是數據類型
{
return t1?t2;//?表示你要的運算方式
}
- 3 回答
- 0 關注
- 753 瀏覽
添加回答
舉報
