C++ 使用常量变量作为数组的大小
为什么编译以下代码段时没有错误:C++ 使用常量变量作为数组的大小,c++,arrays,class,constants,C++,Arrays,Class,Constants,为什么编译以下代码段时没有错误: 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 };
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
我在其他类似的帖子中找不到令人信服的答案。作为一个非静态数据成员,它可能通过不同的初始化方式(构造函数(成员初始值设定项列表)、默认成员初始值设定项、聚合初始化等)使用不同的值进行初始化。在初始化之前,不会确定其值。但原始数组的大小必须在编译时固定并已知。e、 g
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} {}
};
数组的长度必须是常量表达式,