问题描述
我尝试在堆叠上将固定大小分配给整数数组。
#include<iostream>
using namespace std;
int main(){
int n1 = 10;
const int N = const_cast<const int&>(n1);
//const int N = 10;
cout<<" N="<<N<<endl;
int foo[N];
return 0;
}
但是,这会在最后一行使用 N
定义一个固定的
错误C2057:预期常量表达式
。
However, this gives an error on the last line where I am using N
to define a fixederror C2057: expected constant expression
.
但是,如果我将 N
定义为 const int N = 10
,代码编译就好了。
我应该如何输入 n1
来作为 const int
?
However, if I define N
as const int N = 10
, the code compiles just fine.How should I typecast n1
to trat it as a const int
?
我试过: const int N = const_cast< const int>(n1)
编辑:我使用MS VC ++ 2008编译这个...使用g ++它编译良好。
EDIT : I am using MS VC++ 2008 to compile this... with g++ it compiles fine.
推荐答案
数组的大小必须是所谓的积分常数表达式(ICE)。该值必须在编译时可计算。一个 const int
(或其他const限定的整数类型对象)只有在它本身用一个积分常数表达式初始化时才能用于积分常数表达式。
The size of the array must be what is called an Integral Constant Expression (ICE). The value must be computable at compile-time. A const int
(or other const-qualified integer-type object) can be used in an Integral Constant Expression only if it is itself initialized with an Integral Constant Expression.
一个非const对象(如 n1
)不能出现在积分常数表达式的任何位置。
A non-const object (like n1
) cannot appear anywhere in an Integral Constant Expression.
您是否考虑过使用 std :: vector< int>
?
[注意 - 演员是完全不必要的。以下两者完全相同:
[Note--The cast is entirely unnecessary. Both of the following are both exactly the same:
const int N = n1;
const int N = const_cast<const int&>(n1);
- 结束注]
这篇关于如何转换int到const int在堆栈分配数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!