亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C++如何重載加法運算符?

C++如何重載加法運算符?

C++
MYYA 2019-04-08 08:04:04
C++如何重載加法運算符?
查看完整描述

3 回答

?
SMILET

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來說,重載了加運算符與自動遞增運算符,重載的運算符完成了同類型對象的加運算和遞增運算過程。


查看完整回答
反對 回復 2019-04-09
?
婷婷同學_

TA貢獻1844條經驗 獲得超8個贊

應該這樣可以吧,
int operator + (const T & t1,T & t2) //T是數據類型
{
return t1?t2;//?表示你要的運算方式
}

查看完整回答
反對 回復 2019-04-09
  • 3 回答
  • 0 關注
  • 753 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號