奇怪的错误 C2131:表达式在 VC 2015 中未计算为常量

Strange error C2131: expression did not evaluate to a constant in VC 2015

本文关键字:2015 计算 常量 VC 错误 C2131 表达式      更新时间:2023-10-16
// foo.hpp file 
class foo 
    { 
    public: 
      static const int nmConst; 
      int arr[nmConst]; // line 7 
    };  
// foo.cpp file 
    const int foo::nmConst= 5; 

编译器 VC 2015 返回错误:

1>foo.h(7(:错误 C2131:表达式未计算为常量
1> 1>foo.h(7(:失败是由非常量参数
或 对非常量符号 1> 1>foo.h(7( 的引用: 注意:请参阅用法 "nmConst">

为什么?nmConst是静态常量,其值在*.cpp文件中定义。

可以使用

static const int成员作为数组大小,但您必须在 .hpp 文件中的类中定义此成员,如下所示:

class foo
{
public:
    static const int nmConst = 10;
    int arr[nmConst];
};

这将起作用。

附言关于它背后的逻辑,我相信编译器希望在遇到类声明时立即知道数组成员的大小。如果你在类中不定义static const int成员,编译器会明白你正在尝试定义可变长度数组并报告错误(它不会等待查看你是否真的在某个地方定义了nmconst(。