如何将int转换为const int以在堆栈上分配数组大小
How to convert int to const int to assign array size on stack?
我正在尝试将固定大小的堆栈分配给整数数组
#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
定义固定
的最后一行出现了错误CCD_ 2。
但是,如果我将N
定义为const int N = 10
,那么代码编译得很好。我应该如何键入n1
以将其转换为const int
?
我尝试过:const int N = const_cast<const int>(n1)
,但出现错误。
编辑:我正在使用MS VC++2008编译这个。。。使用g++,它编译得很好。
我应该如何对
n1
进行类型转换以将其视为const int
?
你不能,不是为了这个目的。
数组的大小必须是所谓的积分常数表达式(ICE)。该值在编译时必须是可计算的。只有当const int
(或其他const限定的整数类型对象)本身用Integral Constant Expression初始化时,才能在Integral ConstantExpression中使用。
非常量对象(如n1
)不能出现在积分常量表达式中的任何位置。
您是否考虑过使用std::vector<int>
?
[注意--强制转换是完全没有必要的。以下两项完全相同:
const int N = n1;
const int N = const_cast<const int&>(n1);
--结束注释]
只有固定大小的数组才能以这种方式分配。动态分配内存(int* foo = new int[N];
)并在完成后将其删除,或者(最好)使用std::vector<int>
。
(编辑:GCC接受它作为扩展,但它不是C++标准的一部分。)
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 我的 int main() 中出现堆栈溢出错误
- 将大双精度转换为无符号 int 期间堆栈损坏
- 我如何转换一个基于动态的,基于指针的int堆栈,以便将其打印成字符串
- <int> 在不破坏堆栈的情况下获取 C++ 中的堆栈总和
- 尝试使用堆栈创建队列.为什么我会遇到int转换错误的空白
- 如何在不使用堆栈或数组的情况下从INT中提取每个数字?(C )
- 堆栈(int = 10),这个语法是什么意思(C++)
- 关于运行良好的堆栈RPN程序上的char/int
- C++ 堆栈泛型类,int 变量将 32765 作为值而不是 1
- 在 C++ 中实现 int 堆栈
- 在 c++ 中 int 数组周围堆栈损坏错误
- 在c++中添加int数组时,试图找出堆栈损坏的问题
- 在堆栈<int>上使用 std::max_element
- 如何将int转换为const int以在堆栈上分配数组大小
- (C++内存管理)如果我们有一个 int x = 1234,并且 int &y = x...那么堆栈上 y 的地址是什么?