如同上面重載加法運(yùn)算符一樣,非常簡單 只要在定義和實(shí)現(xiàn),把+改成相應(yīng)的其它算術(shù)運(yùn)算符號就行啦 在函數(shù)實(shí)現(xiàn)部分只要把兩個(gè)對象的各個(gè)成員分別進(jìn)行相應(yīng)的算術(shù)運(yùn)算就行啦, 然后返回計(jì)算結(jié)果的臨時(shí)對象就OK啦 實(shí)例代碼 class OpOver { public: OpOver(int i=0;int j=0){a=i;b=j;}; OpOver& operator+(const OpOver&)const; OpOver& operator-(const OpOver&)const; OpOver& operator*(const OpOver&)const; OpOver& operator/(const OpOver&)const; OpOver& operator%(const OpOver&)const; private: int a; int b; }; //用類成員函數(shù)重載運(yùn)算符+ OpOver& OpOver::operator+(OpOver&& left,const OpOver& right) { OpOver& tempclass(left); tempclass.a+=right.a; tempclass.b+=right.b; return tempclass; } //用類成員函數(shù)重載運(yùn)算符- OpOver& OpOver::operator-(OpOver&& left,const OpOver& right) { OpOver& tempclass(left); tempclass.a-=right.a; tempclass.b-=right.b; return tempclass; } //用類成員函數(shù)重載運(yùn)算符* OpOver& OpOver::operator*(OpOver&& left,const OpOver& right) { OpOver& tempclass(left); tempclass.a*=right.a; tempclass.b*=right.b; return tempclass; } //用類成員函數(shù)重載運(yùn)算符/ OpOver& operator/(OpOver&& left,const OpOver& right) { //要檢查right的各個(gè)成員不能為0 if (right.a!=0 && right.b!=0 ) { OpOver& tempclass(left); tempclass.a/=right.a; tempclass.b/=right.b; return tempclass; } } //用類成員函數(shù)重載運(yùn)算符% OpOver& OpOver::operator%(OpOver&& left,const OpOver& right) { //要檢查right的各個(gè)成員不能為0 if (right.a!=0 && right.b!=0 ) { OpOver& tempclass(left); tempclass.a%=right.a; tempclass.b%=right.b; return tempclass; } }
|