【发布时间】:2021-03-06 02:08:44
【问题描述】:
我在函数中定义了一个类。该类类型的对象稍后在函数中实例化,我想在该类中定义一个常量,该常量是从函数中引用的。
Live code
void foo() {
class Internal {
public:
// here is the constant !!!
static constexpr int NONE = std::numeric_limits<int>::max();
// ------------------------
Internal(int n = NONE) : _n(n) {}
int get() const { return _n; }
private:
int _n;
};
Internal x(123), y;
if (x.get() == Internal::NONE) {
std::cout << "x" << std::endl; // not printed
}
if (y.get() == Internal::NONE) {
std::cout << "y" << std::endl; // printed
}
}
这会产生编译错误:
错误:本地类 'class foo()::Internal' 不应有静态数据成员 'constexpr const int foo()::Internal::NONE' [-fpermissive]
删除static,只留下constexpr,结果:
错误:非静态数据成员“NONE”声明为“constexpr”
仅使用 const 会导致:
错误:非静态数据成员'foo()::Internal::NONE'的使用无效
FWIW,static const 也不起作用。
除了将常量移出类范围之外,还有什么方法可以做到这一点?
【问题讨论】:
-
期待后续问题,给出无法完成的答案:Why not?
标签: c++