如何将int转换为const int以在堆栈上分配数组大小

How to convert int to const int to assign array size on stack?

本文关键字:int 堆栈 分配 数组 转换 const      更新时间:2023-10-16

我正在尝试将固定大小的堆栈分配给整数数组

#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++标准的一部分。)