歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++前置++與後置++的區別與重載

C++前置++與後置++的區別與重載

日期:2017/3/1 9:16:58   编辑:Linux編程

C++前置++與後置++的區別與重載

++屬於單目運算符,前置與後置的實現代碼不一樣,下面以整數自增為例:

// 前置++,返回自增後的值,且返回的是一個左值
int& operator++(){
    *this += 1;
    return *this;
} 

// 後置++,返回自增前的值,且返回的是一個右值
const int operator++(int){
    int temp(*this);
    *this += 1;
    return temp;
}

1、返回值以及返回類型的區別示例如下:

int a = 0, b = 0;
cout << a++ << " " << ++b << endl; // 輸出 0 1
a++ = 9;         // 錯誤,不能對右值類型賦值
++b = 2;         // 正確,b = 2
int c = ++b = 9; // 正確,b = 9,c = 9

2、自定義類重載前置++與後置++,如下例重載鏈表節點:

class Node{
public:
    Node():val(0), next(NULL){}
    
    // 重載前置++,若next為空,則不自增且返回自己
    Node& operator++(){
        if(next == NULL){
            return *this;
        }
        val = next->val;
        next = next->next;
        return *this;
    } 
    
    // 後置++,若next為空,則不自增
    const Node operator++(int){
        if(next == NULL){
            return *this;
        }
        Node temp = *this;
        val = next->val;
        next = next->next;
        return temp;
    }
public:
    int val;
    Node *next;
};

Copyright © Linux教程網 All Rights Reserved