奇怪的错误C2131:表达式在VC 2015中没有评估为常量

use*_*441 1 c++ visual-studio-2015

// foo.hpp file 
class foo 
    { 
    public: 
      static const int nmConst; 
      int arr[nmConst]; // line 7 
    };  
// foo.cpp file 
    const int foo::nmConst= 5; 
Run Code Online (Sandbox Code Playgroud)

编译VC 2015返回错误:

1> foo.h(7):错误C2131:表达式没有求值为常量
1> 1> foo.h(7):失败是由非常量参数引起的或
引用非常量符号1> 1> foo.h(7):注意:看看'nmConst'的用法

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

dba*_*ric 5

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

class foo
{
public:

    static const int nmConst = 10;
    int arr[nmConst];

};
Run Code Online (Sandbox Code Playgroud)

这会奏效.

PS关于它背后的逻辑,我相信编译器一旦遇到类声明就想知道数组成员的大小.如果你static const int在类中保留未定义的成员,编译器将会理解你正在尝试定义可变长度数组并报告错误(它不会等到你是否真的定义了nmconst某个地方).