我想找这个,但找不到。我知道我可以创建对数组变量的引用:
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]”的引用不能绑定(bind)到不相关类型“int [n]”的值。任何人都知道如何解决这个问题?提前致谢。
最佳答案
运行时长度数组是 C99 的一个特性,标准 C++ 中不存在。它们作为某些 C++ 编译器的扩展存在,但不能很好地与 C++ 功能(如引用和模板)混合。
您可能应该使用 vector 。
关于c++ - 引用在运行时确定大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32218011/