C++學習筆記(5)----重載自增自減運算符


  自增運算符“++”和自減運算符“--”分別包含兩個版本。即運算符前置形式(如 ++x)和運算符后置形式(如 x++),這兩者進行的操作是不一樣的。因此,當我們在對這兩個運算符進行重載時,就必須區分前置和后置形式。C++根據參數的個數來區分前置和后置形式。如果按照通常的方法來重載 ++ 運算符(即作為成員函數重載時不帶參數,或者作為非成員函數重載時帶有一個參數),那么重載的是前置版本。要對后置形式進行重載,即 x++ 或 x--,就必須為重載函數再增加一個 int 類型的參數。該參數僅僅用來告訴編譯器這是一個運算符后置形式,在實際調用時不需要給出實際的參數值。

示例,定義一個重載了前置 ++ 和后置 ++ 運算符的 Integer 類:

#include<iostream>
using namespace std;

class Integer {
public :
    Integer(int num) {
        value = num;
    }
    Integer() {
        Integer(0);
    }

    friend ostream& operator <<(ostream& os, Integer& integer);
    
    Integer& operator ++()//前置形式
    {
        this->value++;
        return *this;
    }

    const Integer operator++(int)    //后置形式
    {
        Integer tmp(this->value);
        this->value++;
        return tmp;
    }

    int getValue() const;
    int setValue(int num);
private:
    int value;
};


int Integer::getValue() const
{
    return value;
}
int Integer::setValue(int num)
{
    value = num;
    return value;
}

ostream& operator <<(ostream& os, Integer& integer)
{
    os << integer.value;
    return os;
}

int main(int argc, char* argv[])
{
    Integer num(10);
    cout << "num=" << num << endl;
    auto value = num++;
    cout << "num++=" << value << endl;
    cout << "now num=" << num << endl;
    value = ++num;
    cout << "++num=" << value << endl;
    
    return 0;
}

運行結果如下:

S:\Debug>string.exe
num=10
num++=10
now num=11
++num=12

 


免責聲明!

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



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