如何在 C++ 中将 const int 设置为最大值?

How to set a const int to maximum in C++?

我有一个静态常量成员,想将它设置为最大整数。我正在尝试以下操作:

const static int MY_VALUE = std::numeric_limits<int>::max();

但是出现如下错误:

error: in-class initializer for static data member is not a constant expression

有什么解决办法吗?一个函数怎么能不是return一个常量表达式呢?

编辑: 添加 -std=c++11 解决了这个问题。我的室友告诉我,编译器(C++11 之前的版本)不够聪明,无法决定 std::numeric_limits::max() 不会改变任何其他内容,因此不被视为常量。这可能是此错误的原因吗?

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions.

The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

numeric_limits max() 不是整数常数,那是编译时间常数。

必须从常量表达式(可在编译时计算的表达式)初始化常量。

在 C++03 中,可以从中构建常量表达式的常量操作集非常紧凑。只有裸积分和数学运算。

为了在常量表达式中使用用户定义的函数,您需要:

  • C++11 或更高版本
  • 表示要标注的功能constexpr

这就是为什么将 -std=c++11 标志添加到 Clang 有帮助的原因:它允许 constexpr 和 "switched" 到改进的标准库实现中,该实现使用 constexpr 作为 [=14] =].

注意:如果您使用较新版本的 Clang,C++11 将是默认版本,并且不需要标志来允许 constexpr.

像这样:

#include <climits>
const static int MY_VALUE = INT_MAX;