C++中操作符++的实现

重载操作符++

  ++有两种使用方法,一种a++,一种++a。刚学的时候一脸蒙蔽也不知道这样有何意义,后来得知其中的区别。下面记录一下我的学习记录。

a++实现:

    const int operator++(int)
    {
        int temp = a;
        a=a+1;
        return temp;//该处返回的是一个值
    }

++a实现:

    base& operator++()
    {
        a+=1;
        return *this;//返回当前对象
    }

 

1、因为值不能为左值,所以a++不能为左值。++a可以为左值。

2、再者可以看出,a++返回的是加之前的值temp。++a返回的本对象(加之后的值)。这也就能解释为什么++a先自加,a++后自加。

posted @ 2018-09-25 11:46  roy_loong  阅读(582)  评论(0)    收藏  举报