使用常量变量作为数组的大小
Using a constant variable as the size of an array
为什么编译以下代码片段没有错误:
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} {}
};
相关文章:
- 是默认情况下分配给char数组常量的值
- 如何创建长度由常量参数指定的数组
- C++常量数组的编译时间较长
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 使用双指针传递 2D 常量数组
- 将字符串数组传递给接受常量字符**的函数
- 检查输入 std::array 指针数据是否等于某个常量数组
- 为什么不能用常量表达式声明数组?
- 如何在可执行文件中存储常量数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 初始化常量字符* 数组
- C++将常量字符* 指针数组传递给对象
- 初始化不是整数的巨大常量多维数组的最佳方法是什么?
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- 为什么不建议使用宏符号常量定义一个固定长度的数组呢
- 我可以使用常量定义数组的长度,那么为什么 int d[b] 不起作用呢?
- 如何为包含另一个类实例的数组制作常量 getter?
- LLVM 无法将数组类型强制转换为常量数组
- 如何删除#define使用在c++数组常量
- 静态数组常量是否会影响共享库布局