c++参考数组
我不知道如何才能使这段代码工作?
#include <iostream>
using namespace std;
void writeTable(int (&tab)[],int x){
for(int i=0;i<x;i++){
cout << "Enter value " << i+1 <<endl;
cin >> tab[i] ;
}
}
int main(void){
int howMany;
cout << "How many elemets" << endl;
cin >> howMany;
int table[howMany];
int (&ref)[howMany]=table;
writeTable(ref,howMany);
return 0;
}
这是我遇到的错误:
|4|error: parameter ‘tab’ includes reference to array of unknown bound ‘int []’|
|18|error: invalid initialization of reference of type ‘int (&)[]’ from expression of type ‘int [(((unsigned int)(((int)howMany) + -0x00000000000000001)) + 1)]’|
|4|error: in passing argument 1 of ‘void writeTable(int (&)[], int)’|
感谢您的帮助
I wounder how i can make this code work?
#include <iostream>
using namespace std;
void writeTable(int (&tab)[],int x){
for(int i=0;i<x;i++){
cout << "Enter value " << i+1 <<endl;
cin >> tab[i] ;
}
}
int main(void){
int howMany;
cout << "How many elemets" << endl;
cin >> howMany;
int table[howMany];
int (&ref)[howMany]=table;
writeTable(ref,howMany);
return 0;
}
And here are the errors that I have:
|4|error: parameter ‘tab’ includes reference to array of unknown bound ‘int []’|
|18|error: invalid initialization of reference of type ‘int (&)[]’ from expression of type ‘int [(((unsigned int)(((int)howMany) + -0x00000000000000001)) + 1)]’|
|4|error: in passing argument 1 of ‘void writeTable(int (&)[], int)’|
Thanks for help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您打算传递数组的大小,那么删除引用
相当于
不会进行任何复制(如果这是问题的话)。
如果您想通过引用获取数组,则必须指定维度。例如
,自然地,两者中最好的是第三种解决方案,即使用 std::vector 并通过引用、对 const 的引用或按值(如果需要)传递它们。华泰
If you are intending to pass the size of the array, then remove the reference
is equivalent to
so no copying will be done, if that is the concern.
If you want to take an array by reference, then you MUST specify the dimension. e.g.
Naturally, the best of the two is the third solution, which is to use std::vector's and pass them by reference, reference to const or by value if needed. HTH
下面是一种稍微更 C++ 的风格:
Here is a slightly more C++ style of doing it:
如果将 writeTable 设为函数模板,则无需指定数组的维数。
。
You need not specify the dimension of the array if you make
writeTable
a function template..
根据 Amardeep 的回答,这是一种 C++11 方法:
请注意
writeTable
中使用的基于范围的for
。Following Amardeep's answer, here is a C++11 way to do it:
Note the range-based
for
used inwriteTable
.如果您想要这样做,则引用数组是非法的。从标题中我并不能100%清楚。
Arrays of references are illegal, if that is what you are trying to do. It's not 100% clear to me from the title.