简体   繁体   English

C ++声明数组,其大小值来自const数组

[英]C++ Declare array whose size value from const array

I'm trying to define a stack c-style array whose size is taken from const array and is known in compile-time. 我试图定义一个堆栈c样式数组,其大小取自const数组,并且在编译时已知。

const int size[2]={100, 100};
int ar[size[0]]; //error: expression must have a constant value

It fails. 它失败。 How it can be fixed? 如何解决?

"array whose size is taken from const array and is known in compile-time " “数组的大小取自const数组,并且在编译时已知”

With C++11 you can have : 使用C ++ 11,您可以:

constexpr int size[2]={100, 100}; // size[0] is Compile-time constant

Use -std=c++11 or -std=c++0x to compile 使用-std=c++11-std=c++0x进行编译

Some options (with varying degrees of popularity): 一些选项(受欢迎程度不同):

  1. Use constexpr (not supported in Visual Studio) 使用constexpr(Visual Studio不支持)
  2. Use a Vector 使用向量
  3. Use dynamic allocation 使用动态分配
  4. Use a const int (C99 or newer or C++) 使用const int (C99或更高版本或C ++)
  5. Use an enum 使用一个enum
  6. Use a MACRO to define the size (since it's known at compile time) 使用MACRO定义大小(因为在编译时已知)

C++ array sizes must be constant expressions, not just constant data. C ++数组大小必须是常量表达式,而不仅仅是常量数据。 Array data, even though const, is not a constant expression. 即使const,数组数据也不是常量表达式。

array size and const 数组大小和常量

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

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