[C++] 前置++与后置++

首先需要明确一个概念,就是*p++与(*p)++的区别。

*p++:对p取值,然后对p指针增加。

(*p)++:对p取值,然后对值增加。

 

++a:表示取a的地址,对a的值进行增加,然后把这个值放入寄存器。结果可以作为左值。

实现代码如下:

// return a reference that means this value can be a left-value.
int& int::operator++() {
    // the empty param means add one in itself space.
    // plus one.        
    *this += 1;
    // return value.
    return *this;
}

 

a++:表示取a的地址,把这个值放入寄存器,然后对内存中的a值进行增加。

实现代码如下:

// the return value is not a left-value.
const int int::operator(int) {
    // the param is existed that means the param occupy space.
    // set old value.
    int oldValue = *this;
    // plus one in origin value.
    ++(*this);
    // return old value.
    return oldValue;
}

 

posted @ 2017-12-06 10:41  immjc  阅读(209)  评论(0编辑  收藏  举报