繁体   English   中英

将 `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

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

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

问候!

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

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

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

那将是:

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

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

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

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

我在以下语句中实现了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将在运行时评估。 因此无法使用将在运行时评估的数字设置char buffer数组长度,我们需要一个量值。

注意:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM