zer*_*00l 2 c++ arrays struct visual-c++
我正在学习 C++ 中的引用。是否无法创建对结构数组的引用?
struct student {
char name[20];
char address[50];
char id_no[10];
};
int main() {
student test;
student addressbook[100];
student &test = addressbook; //This does not work
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
类型“student &”(非 const 限定)的引用无法使用类型“student [100]”的值进行初始化错误
C2440“初始化”:无法从“student [100]”转换为“student &”
引用的类型必须与其所引用的内容相匹配。对单个学生的引用不能引用 100 名学生的数组。您的选择包括:
// Refer to single student
student &test = addressbook[0];
// Refer to all students
student (&all)[100] = addressbook;
auto &all = addressbook; // equivalent
Run Code Online (Sandbox Code Playgroud)
是的,这是可能的。它只需是正确类型的引用即可。一个学生并不是由 100 名学生组成的数组。但语法有点尴尬:
student (&test)[100] = addressbook;
Run Code Online (Sandbox Code Playgroud)
阅读以下内容后会更有意义:http ://c-faq.com/decl/spiral.anderson.html
您最常看到数组引用的地方可能是作为模板函数的参数,其中推导了数组的大小。
template<typename T, size_t N>
void foo(T (&arr)[N]);
Run Code Online (Sandbox Code Playgroud)
这允许您将数组作为单个参数传递给函数,而不会衰减为指针并丢失大小信息。
在标准库中可以看到这样的一个例子std::begin/end。