【问题标题】:Set an element of a `const` array as the length of another array in c++在c ++中将`const`数组的元素设置为另一个数组的长度
【发布时间】:2021-03-18 00:44:52
【问题描述】:

我像这样定义了一个const int 数组:

const int arr[] = { 100 , 200, 300, 400 };

现在我想将上述数组的元素之一设置为另一个数组的长度,如下所示:

char buffer[arr[3]];

但它给了我一个编译时间error

non-constant arguments or reference to a non-constant symbol

我研究了这个This question 来解决我的问题,但我对这些问题感到困惑:

  • 为什么我不能将const 数组的元素设置为另一个数组的长度?
  • const 数组的元素是常量还是只读的?
  • c 中的const只读 语句有什么区别?

问候!

【问题讨论】:

    标签: c++ arrays c++11 constants


    【解决方案1】:

    C++ 中有两种不同的常量“事物”。

    你知道的 const 关键字:你不能修改它在运行时

    并且在编译时在编译时被称为编译器的常量值。

    那就是:

    constexpr int arr[] = { 100 , 200, 300, 400 };
    

    C++ 要求数组大小为constexpr 表达式,而不仅仅是const 表达式。一些编译器允许您只使用 const 大小(实际上甚至没有),但这不是当前的 C++ 标准。

    您可能想知道为什么在这种情况下,这不是编译时的常量值。毕竟:它就在那里。是三位数。一个整数。它不能去任何地方。

    嗯,这将是一个不同的、迂腐的问题,但大多数情况下是无关紧要的。在这种情况下,您的编译器完全有权拒绝非constexpr 表达式,因为它的格式不正确。确实如此。而且你别无选择,只能服从编译器的要求。

    【讨论】:

    • 我无法在编译和运行时修改 const 和 constexpr。区别在哪里????能解释清楚一点吗?
    • 我发布了一个新答案。请查看我的答案。
    • constexpr 真的应该重命名为reallyconst,因此将const 命名为maybeconstunlessyoudontwantittobe.. 我最喜欢的咆哮之一。
    【解决方案2】:

    我在以下语句中意识到constconstexpr

    • const :在运行时进行评估,它被编译器接受并且不能在运行时更改。

      const int a = std::cin.get();       // correct
      const int b = 5;                    // correct
      
    • constexpr:在编译时进行评估

      constexpr int b = std::cin.get();   // incorrect (because it evaluate in compile time, so compiler cannot forecast the value at compile time)
      constexpr int b = 65;               // correct
      

    据我所知,现在在我的code 中,我认为char buffer 是在编译时 评估数组大小,const int arr 将在 em>运行时。所以不能使用将在 runtime 评估的数字设置 char buffer 数组长度,我们需要一个 constant 值。

    注意:

    const int arr[] = { 100 , 200, 300, 400 };     // Evaluate at runtime
    char buffer[arr[3]];                           // Evaluate at compile time and cause error
    

    所以我们需要一个在编译时评估的const 数字来设置char buffer 的数组长度:

    constexpr int arr[] = { 100 , 200, 300, 400 };     // Evaluate at compile time
    char buffer[arr[3]];                               // Evaluate at compile time
    

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 2018-01-29
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多