将`const`数组的元素设置为c ++中另一个数组的长度

Set an element of a `const` array as the length of another array in c++

我定义了一个 const int 数组,如下所示:

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

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

char buffer[arr[3]];

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

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

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

此致!

C++ 中确实有两种不同的常量“东西”。

您知道的 const 关键字:您无法在运行时修改它.

而编译器在编译时.

知道的常量值

那一个是:

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

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

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

好吧,那将是一个不同的、迂腐的问题,但基本上是无关紧要的。在这种情况下,您的编译器完全有权拒绝非 constexpr 表达式,因为格式错误。确实如此。你别无选择,只能服从编译器的要求。

我在以下语句中实现了 constconstexpr :

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

    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 是在 编译时 [= 评估数组大小54=] 和 const int arr 将在 运行时 进行评估。因此不能使用将在 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 编译时间 计算的数字来设置 [=19= 的数组长度] :

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