[英]literal class compile error with constexpr constructor and function (differ vc, g++)
#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;
}
Why the code above can't compile with MSVC compiler while works with g++? 为什么上面的代码在使用g ++时不能用MSVC编译器编译? Isn't MSVC not as strict as other compilers?
MSVC是否不如其他编译器那么严格? The difference results between MSVC and g++ is sometimes confusing.
MSVC和g ++之间的差异结果有时会令人困惑。 Which compiler should I rely on, any tips btw?
还有什么提示,我应该依靠哪个编译器?
The problem is that a constexpr
object implies const
, which means you cannot call area
as it is a non-const function. 问题在于
constexpr
对象隐含const
,这意味着您不能调用area
因为它是非const函数。 Mark area
as const
and that's it. 将
area
标记为const
就是这样。
Alternatively, making a
non-const will allow you to keep area
non-const, which whilst odd, it's valid C++. 另外,制作
a
非常量将使您可以保持area
非常量,尽管这很奇怪,但它是有效的C ++。
EDIT . 编辑 。 Perhaps you are using C++14 or above.
也许您使用的是C ++ 14或更高版本。 Your impression that a
constexpr
function implies const
is a C++11 feature that was changed in later standards. 您对
constexpr
函数隐含const
印象是C ++ 11功能,该功能在以后的标准中已更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.