使用常量变量作为数组的大小

Using a constant variable as the size of an array

本文关键字:数组 常量 变量      更新时间:2023-10-16

为什么编译以下代码片段没有错误:

void func(){
const int s_max{ 10 };
int m_array[s_max]{0}; 
}
int main() {
const int s_max{ 10 };
int m_array[s_max]{0}; 
return 0;
}

但是当我尝试在类范围内定义相同的数组时,出现以下错误:

class MyClass
{
const int s_max{ 10 }; 
int m_array[s_max]{0}; // error: invalid use of non-static data member 's_max'
};

为什么s_max需要在课堂上static

我无法在其他类似帖子中找到令人信服的答案。

作为非静态数据成员,它可以通过不同的初始化方式(构造函数(成员初始值设定项列表(、默认成员初始值设定项、聚合初始化等(使用不同的值进行初始化。然后,在初始化之前不会确定其值。但是原始数组的大小必须是固定的,并且在编译时是已知的。例如

class MyClass
{
const int s_max{ 10 }; 
int m_array[s_max]{0}; // error: invalid use of non-static data member 's_max'
MyClass(...some arguments...) : s_max {20} {}
MyClass(...some other arguments...) : s_max {30} {}
};