[PE]经典八炮 2021-09-11 09:10 采纳率: 76.9%
浏览 74
已结题

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?

  • 写回答

2条回答 默认 最新

  • 蒟蒻一枚 2021-09-11 09:40
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 9月12日
  • 已采纳回答 9月11日
  • 创建了问题 9月11日

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿