// 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
(。