如何在具有常量类变量的类中声明一个常量数组?是否可以。 我不想要动态数组。
我的意思是这样的:
class test
{
const int size;
int array[size];
public:
test():size(50)
{}
}
int main()
{
test t(500);
return 0;
}
上面的代码报错
最佳答案
不,不可能:只要size
是一个动态变量,array[size]
不可能实现为静态数组。
如果你愿意,可以这样想:sizeof(test)
必须在编译时已知(例如,考虑 test
的数组)。但是sizeof(test) == sizeof(int) * (1 + size)
在您的假设示例中,这不是编译时已知值!
你可以制作size
进入模板参数;这是唯一的解决方案:
template <unsigned int N>
class Test
{
int array[N];
static const unsigned int size = N; // unnecessary really
public:
// ...
};
用法:Test<50> x;
请注意,现在我们有 sizeof(Test<N>) == sizeof(int) * (1 + N)
,这 实际上是一个编译时已知值,因为对于每个 N
, Test<N>
是一个不同的类型。
关于c++ - 如何在具有常量类变量的类中声明常量数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8104777/