【问题标题】:reference to an array of size determined at run-time引用在运行时确定的大小数组
【发布时间】:2015-11-19 23:37:44
【问题描述】:

我试图找到这个但找不到。我知道我可以创建对数组变量的引用:

int x[10] = {}; int (&y)[10] = x;

但是,在编译时不知道数组大小的情况下,如以下代码:

const int n = atoi( string ); //the string is read from a text file at run time.
int x[n] = {}; int (&y)[n] = x; //this generates a compiling error.

即使 int n 被声明为 const,只要 n 在编译时未知,引用就无效。编译器会这样说:对类型“int [n]”的引用不能绑定到不相关类型“int [n]”的值。任何人都知道如何解决这个问题?提前致谢。

【问题讨论】:

    标签: c++ arrays reference variable-length-array


    【解决方案1】:

    运行时长度数组是 C99 功能,在标准 C++ 中不存在。它们作为一些 C++ 编译器的扩展存在,但不能与 C++ 功能(如引用和模板)很好地混合。

    您可能应该使用矢量。

    【讨论】:

      【解决方案2】:

      动态声明数组的特性不应该在 C++ 中使用。并非所有编译器都支持它。考虑改用 STL 容器。赞std::vector<int>

      【讨论】:

        猜你喜欢
        • 2013-12-04
        • 2017-05-23
        • 1970-01-01
        • 2010-12-13
        • 1970-01-01
        • 2015-04-18
        • 1970-01-01
        • 2020-10-04
        • 1970-01-01
        相关资源
        最近更新 更多