#include <iostream>
#include <string>
using namespace std;
class A {
public:
constexpr A() {}
constexpr int area() {
return 12;
}
private:
// constexpr int h = 3;
// constexpr int w = 4;
};
int main()
{
constexpr A a;
constexpr int j = a.area();
cout << j << endl;
}
为什么上面的代码在 g++ 下却不能用 MSVC 编译器编译? MSVC 不是没有其他编译器那么严格吗? MSVC 和 g++ 之间的差异结果有时会令人困惑。我应该依赖哪个编译器,有什么建议吗?
最佳答案
问题是 constexpr
对象隐含 const
,这意味着您无法调用 area
,因为它是非常量函数。将 area
标记为 const
就这样了。
或者,使 a
成为非 const 将允许您保持 area
为非 const,虽然很奇怪,但它是有效的 C++。
编辑。也许您使用的是 C++14 或更高版本。您的印象是,constexpr
函数意味着 const
是一项 C++11 功能,但在后来的标准中已更改。
关于c++ - constexpr 构造函数和函数的文字类编译错误(不同 vc、g++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50146622/