C++ 如何将 int 转换为 const int 以在堆栈上分配数组大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9596650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert int to const int to assign array size on stack?
提问by memC
I am trying to allocate a fixed size on stack to an integer array
我正在尝试将堆栈上的固定大小分配给整数数组
#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;
}
However, this gives an error on the last line where I am using N
to define a fixederror C2057: expected constant expression
.
但是,这在我N
用来定义固定error C2057: expected constant expression
.
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
?
但是,如果我定义N
为const int N = 10
,则代码编译得很好。我应该如何将其转换n1
为 trat const int
?
I tried :const int N = const_cast<const int>(n1)
but that gives error.
我试过:const int N = const_cast<const int>(n1)
但这会出错。
EDIT :I am using MS VC++ 2008 to compile this... with g++ it compiles fine.
编辑:我使用 MS VC++ 2008 来编译这个……用 g++ 编译得很好。
回答by James McNellis
How should I typecast
n1
to treat it as aconst int
?
我应该如何类型转换
n1
以将其视为const int
?
You cannot, not for this purpose.
你不能,不是为了这个目的。
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.
数组的大小必须是所谓的积分常数表达式(ICE)。该值在编译时必须是可计算的。A const int
(或其他 const 限定的整数类型对象)仅当它本身用积分常数表达式初始化时才可以在积分常数表达式中使用。
A non-const object (like n1
) cannot appear anywhere in an Integral Constant Expression.
非常量对象(如n1
)不能出现在积分常数表达式中的任何地方。
Have you considered using std::vector<int>
?
你考虑过使用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);
--End Note]
--尾注]
回答by DCoder
Only fixed-size arrays can be allocated that way. Either allocate memory dynamically (int* foo = new int[N];
) and delete it when you're done, or (preferably) use std::vector<int>
instead.
只能以这种方式分配固定大小的数组。动态分配内存 ( int* foo = new int[N];
) 并在完成后将其删除,或者(最好)std::vector<int>
改为使用。
(Edit: GCC accepts that as an extension, but it's not part of the C++ standard.)
(编辑:GCC 接受它作为扩展,但它不是 C++ 标准的一部分。)