【问题标题】:How to convert int to const int to assign array size on stack?如何将 int 转换为 const int 以在堆栈上分配数组大小?
【发布时间】:2012-03-24 16:42:03
【问题描述】:

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

#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 定义固定
error C2057: expected constant expression 的最后一行出现错误。

但是,如果我将N 定义为const int N = 10,则代码编译得很好。 我应该如何将n1 转换为const int

我试过了: const int N = const_cast&lt;const int&gt;(n1) 但这会出错。

编辑:我正在使用 MS VC++ 2008 来编译它...使用 g++ 编译得很好。

【问题讨论】:

    标签: c++ stack integer constants


    【解决方案1】:

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

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

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

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

    您是否考虑过使用std::vector&lt;int&gt;

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

    const int N = n1;
    const int N = const_cast<const int&>(n1);
    

    --尾注]

    【讨论】:

    • 再补充一点:gcc 将其编译为扩展——事实上,它允许其他甚至不符合要求的表达式,例如int x(int a) { int b[a]; }
    • 啊,谢谢你,@JerryCoffin。我发帖时没有看到编辑。
    • 我们可以选择constexpr int,而不是const int,这样编译器将确保在分配期间值是ICE,而不是在您尝试分配数组时。
    【解决方案2】:

    只能以这种方式分配固定大小的数组。动态分配内存 (int* foo = new int[N];) 并在完成后将其删除,或者(最好)改用 std::vector&lt;int&gt;

    (编辑:GCC accepts that as an extension,但它不是 C++ 标准的一部分。)

    【讨论】:

      猜你喜欢
      • 2012-09-28
      • 2020-12-14
      • 2016-11-11
      • 2014-09-20
      • 2013-01-19
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多