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

标签 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 }; 
    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/

相关文章:

java - Java 中的类之间进行通信?

java - 没有经验的 java 用户请求有关类的建议

java - 与 Java 对象混淆

java - 如何计算ArrayList中重复单词的数量(不使用Hash)

c++ - 删除指向数组 C++ 的数组指针时出错

c++ - 将 int8 转换为 int7 的最快方法

Java 比较器 Arrays.sort()

c++ - 许多具有相同构造函数的类

C++ vector 源代码

c++ - QTree控件;在 QTree 中选择多个项目时禁用 ui 功能