c++声明数组,它的大小值来自const数组

时间:2021-05-10 21:30:20

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?

它失败。如何修复?

3 个解决方案

#1


3  

"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

大小constexpr int[2]= { 100、100 };//尺寸[0]是编译时常数。

Use -std=c++11 or -std=c++0x to compile

使用-std=c++11或-std=c++0x进行编译

#2


2  

Some options (with varying degrees of popularity):

一些选择(受欢迎程度不同):

  1. Use constexpr (not supported in Visual Studio)
  2. 使用constexpr(在Visual Studio中不支持)
  3. Use a Vector
  4. 使用一个向量
  5. Use dynamic allocation
  6. 使用动态分配
  7. Use a const int (C99 or newer or C++)
  8. 使用const int (C99或更新或c++)
  9. Use an enum
  10. 使用一个枚举
  11. Use a MACRO to define the size (since it's known at compile time)
  12. 使用宏来定义大小(因为它在编译时是已知的)

#3


1  

C++ array sizes must be constant expressions, not just constant data. Array data, even though const, is not a constant expression.

c++数组大小必须是常量表达式,而不仅仅是常量数据。数组数据,即使是const,也不是一个常量表达式。

array size and const

数组大小和常量

#1


3  

"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

大小constexpr int[2]= { 100、100 };//尺寸[0]是编译时常数。

Use -std=c++11 or -std=c++0x to compile

使用-std=c++11或-std=c++0x进行编译

#2


2  

Some options (with varying degrees of popularity):

一些选择(受欢迎程度不同):

  1. Use constexpr (not supported in Visual Studio)
  2. 使用constexpr(在Visual Studio中不支持)
  3. Use a Vector
  4. 使用一个向量
  5. Use dynamic allocation
  6. 使用动态分配
  7. Use a const int (C99 or newer or C++)
  8. 使用const int (C99或更新或c++)
  9. Use an enum
  10. 使用一个枚举
  11. Use a MACRO to define the size (since it's known at compile time)
  12. 使用宏来定义大小(因为它在编译时是已知的)

#3


1  

C++ array sizes must be constant expressions, not just constant data. Array data, even though const, is not a constant expression.

c++数组大小必须是常量表达式,而不仅仅是常量数据。数组数据,即使是const,也不是一个常量表达式。

array size and const

数组大小和常量