Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用常量变量作为数组的大小_C++_Arrays_Class_Constants - Fatal编程技术网

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} {}
};

数组的长度必须是常量表达式, const 是必要的,但对于常量表达式是不够的。我有一些坏消息:即使第一个片段“编译无错误”,它也不是有效的C++。你的编译器只是帮了你一个忙,允许一些不标准的C++。@ SamVarshavchik,我认为这第一种情况应该是好的;code>s_max是一个。具有整型或枚举类型,并引用一个完整的非易失性const对象,该对象使用常量表达式初始化,因此当我们将其设置为静态(并且必须为其赋值)时,它将在编译时已知,并且不依赖于不同的初始化,对吗?@Monaj Yes,静态成员不能以不同的方式初始化。