对结构数组的引用

Reference to array of struct

本文关键字:引用 数组 结构      更新时间:2023-10-16

我正在学习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
}

得到以下错误:

类型为"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

这是可能的。它只需要是正确类型的引用。学生不是由100个学生组成的数组。语法有点别扭:

student (&test)[100] = addressbook;

一旦你读了这个就会更有意义:http://c-faq.com/decl/spiral.anderson.html

数组引用最常见的地方可能是作为模板函数的实参,其中数组的大小是推导出来的。

template<typename T, size_t N>
void foo(T (&arr)[N]);

这允许你将数组作为单个参数传递给函数,而不会衰变成指针并丢失大小信息。

在标准库std::begin/end中可以看到一个这样的例子。