C++前置与后置

对于迭代器和其他模板对象使用前缀形式 (++i) 的自增, 自减运算符,理由是 前置自增 (++i) 通常要比后置自增 (i++) 效率更高。

  ++a表示取a的地址,增加它的内容,然后把值放在寄存器中;
 a++表示取a的地址,把它的值装入寄存器,然后增加内存中的a的值;

前缀与后缀运算符重载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Age     
{
public:

Age& operator++() //前置++
{
++i;
return *this;
}

const Age operator++(int) //后置++
{
Age tmp = *this;
++(*this); //利用前置++
return tmp;
}

Age& operator=(int i) //赋值操作
{
this->i = i;
return *this;
}

private:
int i;
};

int main()
{
Age a;

(a++)++; //编译错误 (右值)
++(a++); //编译错误 (右值)
a++ = 1; //编译错误 (右值)
(++a)++; //OK
++(++a); //OK
++a = 1; //OK
}
a++的类型是const Age,返回的是右值,自然不能对它进行前置++、后置++、赋值等操作。同时会产生临时对象。

++a的类型是Age&,返回的是左值,当然可以对它进行前置++、后置++、赋值等操作

所以,在非内置类型的时候,尽量使用前置++,因为效率高(后置自增,效率低)