为什么下面的代码片段编译没有错误:
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} {}
};
关于c++ - 使用常量变量作为数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57618970/