C++前置++与后置++的问题


#include<iostream>
class MyClass
{
public:
    int i;
    MyClass operator+=(int j)
    {
        i += j;
        return *this;
    }
    MyClass operator+(const MyClass& b)
    {
        MyClass tmp;
        tmp.i = this->i + b.i;
        return tmp;
    }
    MyClass operator++()//前置++
    {
        return *this += 1;
    }
    MyClass operator++(int)//后置++
    {
        MyClass temp = *this;
        *this += 1;
        return temp;
     }
};
int main()
{
    int i = 2;
    int result = i++ + i++ + i++;
    std::cout << result << '\t' << i << std::endl;
    i = 2;
    result = ++i + ++i + ++i;
    std::cout << result << '\t' << i << std::endl;
    MyClass a;
    a.i = 2;
    MyClass result2 = a++ + a++ + a++;
    std::cout << result2.i << '\t' << a.i << std::endl;
    a.i = 2;
    result2 = ++a + ++a + ++a;
    std::cout << result2.i << '\t' << a.i << std::endl;
}

同样的代码,vs中的运行结果是

img


dev-c的运行结果是

img


其它的都好理解,我不明白的是


     int i = 2;
    int result = ++i + ++i + ++i;

在dev中的结果为什么是13?

对于++i + ++i + ++i这个表达式,编译器首先扫描的是前半部分,也就是先算出++i + ++i。
先对i++两次,i = 4,再计算i+i的值为4 + 4=8。
然后再看后半部分,就是++i。
此时的i为4,++i后i为5,所以结果为8 + 5 = 13.

要是想让编译器分别处理每个++i,就要用volatile关键字修饰变量i,即:
volatile int i = 2;
int result = ++i + ++i + ++i;