C++11 iso 标准对这样的表达式是怎么说的:
class MyClass
{
public:
constexpr int test()
{
return _x;
}
protected:
int _x;
};
_x
是 constexpr
中使用的非常量:它会产生错误,还是会简单地忽略 constexpr
(如当我们传递一个非常量参数时)?
最佳答案
非常好,虽然有点没用:
constexpr int n = MyClass().test();
因为 MyClass
是一个集合,像这样对它进行值初始化将对所有成员进行值初始化,所以它只是零。但经过一些润色,这可以变得真正有用:
class MyClass
{
public:
constexpr MyClass() : _x(5) { }
constexpr int test() { return _x; }
// ...
};
constexpr int n = MyClass().test(); // 5
关于c++ - 在 constexpr : what does the standard say? 中使用非常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12605552/