我有一个C2057错误(在Visual Studio 2010上),我不知道为什么.我理解要初始化堆栈上的数组,必须在编译时知道大小,这就是为什么你需要使用const值(至少在Visual Studio上,因为不允许像gcc那样使用可变长度数组).我的类中有一个const值成员,我在初始化列表中定义了它的值.从技术上讲,这个价值在编译时是否已知?我想明白为什么它不起作用?这是一个片段:
class Dummy
{
Dummy() : size(4096) {}
void SomeFunction()
{
int array[size]; //return C2057
//...
}
const unsigned int size;
};
Run Code Online (Sandbox Code Playgroud)
谢谢
不幸的是,这个const值不是编译时常量.您需要枚举,静态整数类型或C++ 11 constexpr
.
另一种选择是创建Dummy
一个类模板,采用非类型参数:
template <unsigned int SIZE>
class Dummy
{
void SomeFunction()
{
int array[SIZE];
//...
}
};
Run Code Online (Sandbox Code Playgroud)
size
是const,但在编译时不知道是4096.
默认构造函数创建一个大小为4096的Dummy,但谁说Dummy类不是用不同的大小构造的?如果有另一个允许不同大小的构造函数,那么编译器不能假设它size
总是4096,所以它给出了编译时错误.