【问题标题】:Using a constant variable as the size of an array使用常量变量作为数组的大小
【发布时间】:2019-12-28 08:19:15
【问题描述】:

为什么下面的代码sn-p编译没有错误:

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

我在其他类似帖子中找不到我的问题的令人信服的答案。

【问题讨论】:

  • 数组的长度必须是常量表达式,const 是必需的,但对于常量表达式是不够的。
  • 我有一个坏消息:即使第一个 sn-p “编译没有错误”,它也不是有效的 C++。您的编译器只是在帮您一个忙,并允许使用非标准 C++ 的内容。
  • @SamVarshavchik 我认为第一种情况应该没问题; s_maxconstant expression具有整型或枚举类型,指的是一个完整的非易失性const对象,用常量表达式初始化

标签: c++ arrays class constants


【解决方案1】:

作为非静态数据成员,它可能通过不同的初始化方式(构造函数(成员初始化器列表)、默认成员初始化器、聚合初始化等)使用不同的值进行初始化。那么它的值在初始化之前不会被确定。但是原始数组的大小必须在编译时是固定的并且是已知的。例如

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

【讨论】:

  • 我明白了,所以当我们将其设为静态时(并且我们还必须为其分配一个值),它会在编译时知道并且不会依赖于不同的初始化,对吧?
  • @Monaj 是的,静态成员不能以不同的不确定方式初始化。
猜你喜欢
  • 2011-02-21
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多