// 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文件中定义。
发布于 2015-11-10 08:07:19
可以使用static const int成员作为数组大小,但您必须在.hpp文件中的类中定义这个成员,如下所示:
class foo
{
public:
static const int nmConst = 10;
int arr[nmConst];
};这会管用的。
P.S.关于它背后的逻辑,我相信编译器想知道数组成员在遇到类声明时的大小。如果您在类中没有定义static const int成员,编译器将理解您试图定义变量长度数组并报告一个错误(它将迫不及待地查看是否在某个地方定义了nmconst )。
https://stackoverflow.com/questions/33625180
复制相似问题