且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-05 21:18:56

我应该如何对 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);

--尾注]