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):
一些选择(受欢迎程度不同):
- Use constexpr (not supported in Visual Studio)
- 使用constexpr(在Visual Studio中不支持)
- Use a Vector
- 使用一个向量
- Use dynamic allocation
- 使用动态分配
- Use a
const int
(C99 or newer or C++) - 使用const int (C99或更新或c++)
- Use an
enum
- 使用一个枚举
- Use a MACRO to define the size (since it's known at compile time)
- 使用宏来定义大小(因为它在编译时是已知的)
#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,也不是一个常量表达式。
数组大小和常量
#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):
一些选择(受欢迎程度不同):
- Use constexpr (not supported in Visual Studio)
- 使用constexpr(在Visual Studio中不支持)
- Use a Vector
- 使用一个向量
- Use dynamic allocation
- 使用动态分配
- Use a
const int
(C99 or newer or C++) - 使用const int (C99或更新或c++)
- Use an
enum
- 使用一个枚举
- Use a MACRO to define the size (since it's known at compile time)
- 使用宏来定义大小(因为它在编译时是已知的)
#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,也不是一个常量表达式。
数组大小和常量