c++ - constexpr 构造函数和函数的文字类编译错误(不同 vc、g++)

标签 c++ compiler-errors

#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++ 之间的差异结果有时会令人困惑。我应该依赖哪个编译器,有什么建议吗?

enter image description here enter image description here

最佳答案

问题是 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/

相关文章:

macos - 在 macos 上调用私有(private)构造函数时出错

objective-c - "Couldn' t 编译连接 :"error mean? 是什么意思

c++ - 在 C++ 中分配 3D 数组最惯用的方法是什么?

c++ - 搜索并发链表

c++ - 调用自动构造函数 : why is my type incomplete?

c - 相同的代码在 gcc 编译器和 Turbo C 中返回不同的值

android - 对 'DTLS_client_method' 的 undefined reference

c++ - C++ 中的内存泄漏 : vector functions in loops

c++ - 正在创建重复的 USB 虚拟串行端口 - 这可能是什么原因造成的?

macos - OS X 10.8 上的 CMAKE、Clang 和 C++v11