C++中自增和自減的實現


C++中自增和自減符號我們經常使用,了解它的實現方式能夠更好的為自己定義的類實現自增和自減。我們首先需要了解一個知識點,自增和自減是通過重載"++"和"--"來實現的,但是普通的重載形式無法區分這兩種情況,為了解決這個情況,后置版本接受一個額外的(不被使用)int類型的形參,編譯器為這個形參提供一個值為0的實參

#include <iostream>
using namespace std;

class Test{
    int a;
    string str;
public:
    Test(int i, string s) : a(i), str(std::move(s)) {}

    Test &operator++(){//前置++
        ++a;
        return *this;
    }

    Test operator++(int){ //后置++,因為此處要返回局部變量,故不能使用引用
        Test ret = *this;
        ++*this;
        return ret;
    }

    Test &operator--(){//前置--
        --a;
        return *this;
    }

    Test operator--(int){ //后置--,因為此處要返回局部變量,故不能使用引用
        Test ret = *this;
        --*this;
        return ret;
    }

    friend ostream& operator<<(ostream &os, const Test &test){
        os << test.str << " : " << test.a << endl;
        return os;
    }
};

int main(){
    Test test(1, "C++");
    cout << test << endl;
    cout << "前置自增 : " << ++test << endl;
    cout << test++ << endl;
    cout << "后置自增 : " << test << endl;
    cout << "前置自減 : " << --test << endl;
    cout << test-- << endl;
    cout << "后置自減 : " << test << endl;
    return 0;
}


輸出:

C++ : 1

前置自增 : C++ : 2

C++ : 2

后置自增 : C++ : 3

前置自減 : C++ : 2

C++ : 2

后置自減 : C++ : 1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM