You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Stroustrup书中constexpr示例在VS C++ 2022中无法编译

问题诊断与解释

错误根源

constexpr修饰的对象属于常量对象,常量对象只能调用const限定的成员函数。你的代码中:

  • constexpr Point p{1,2} 定义了一个常量对象p
  • up()成员函数没有添加const限定,它的this指针类型是Point&(非const)

当常量对象p调用up()时,编译器会尝试将const Point类型的this指针转换为Point&,这会丢失const限定符,因此触发C2662错误。

修正方案

给up()成员函数添加const限定,同时保留constexpr:

struct Point {
    int x, y, z;
    constexpr Point up(int d) const { return { x,y,z + d }; }
};

补充说明

  • 移除p的constexpr后,p变为普通可变对象,普通对象可以调用非const成员函数,因此编译正常。
  • up()函数只是读取成员变量并返回新的Point对象,不会修改原对象,添加const限定完全符合函数的行为逻辑,同时也满足常量对象的调用要求。

内容的提问来源于stack exchange,提问作者AR-47

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 08:40:53