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

2022-01-22 00:00:00 integer stack constants c++

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

#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 fixed
error 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.

推荐答案

我应该如何对 n1 进行类型转换以将其视为 const int?

How should I typecast n1 to treat it as a const int?

你不能,不是为了这个目的.

You cannot, not for this purpose.

数组的大小必须是所谓的积分常数表达式 (ICE).该值必须在编译时可计算.const int(或其他 const 限定的整数类型对象)只有在它本身使用 Integral Constant Expression 初始化时才能在 Integral Constant Expression 中使用.

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.

非常量对象(如 n1)不能出现在整型常量表达式中的任何位置.

A non-const object (like n1) cannot appear anywhere in an Integral Constant Expression.

您是否考虑过使用 std::vector?

[注意――演员表完全没有必要.以下两者完全相同:

[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);

--尾注]

相关文章