C++操作符重載不同方式區(qū)別
作者:佚名
大家在使用C++操作符重載的時(shí)候,往往會(huì)遇到一些麻煩,就是午飯判斷++(--)是在操作數(shù)前面還是在操作數(shù)后面。我們將會(huì)在這里詳細(xì)介紹正確的應(yīng)用方法。
C++編程語言可以被看做是C語言的升級(jí)版本,它能夠支持C語言中的所有功能,而且在其他方面也有很大的提升。其中,在C++操作符重載中++,--需要說明是++(--)在操作數(shù)前面,還是在操作數(shù)后面,區(qū)別如下:
C++操作符重載代碼經(jīng)過測試無誤(起碼我這里沒問題^_^)
- #include < iostream>
- #include < cstdlib>
- using namespace std;
- template< typename T> class A
- {
- public:
- A(): m_(0){
- }
- // +
- const T operator + (const T& rhs)
- {
- // need to be repaired , but see it is only a demo
- return (this->m_ + rhs);
- }
- // -
- const T operator - (const T& rhs){
- // need to be repaired , but see it is only a demo
- return (this->m_ - rhs);
- }
- T getM(){
- return m_;
- }
- // ++在前的模式,這里返回的是引用 ,準(zhǔn)許++++A
- A& operator ++ (){
- (this->m_)++;
- return *this;
- }
- // ++ 在后,這里返回的是一個(gè)新的A類型變量,且不可改變
- // 目的是防止出現(xiàn) A++++情況
- const A operator ++(int a){
- A< T> b = *this;
- (this->m_)++;
- return b;
- }
- private:
- T m_;
- };
- int main(void){
- int i = 0;
- cout< < ++++i< < endl;
- // i++++ is not allowed
- A< int> a;
- A< int> b = ++a;
- cout< < b.getM()< < endl;
- A< int> c = a++;
- cout< < c.getM()< < endl;
- cout< < a.getM()< < endl;
- int t = a+2;
- cout< < t< < endl;
- system("pause");
- return 0;
- }
以上就是對C++操作符重載的相關(guān)介紹。
【編輯推薦】
責(zé)任編輯:曹凱
來源:
博客園