繁体   English   中英

引用结构体数组

[英]Reference to array of struct

我正在学习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“正在初始化”:无法从“学生[100]”转换为“学生&”

引用的类型必须匹配它所引用的内容。 对单个学生的引用不能引用由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的标准库中看到一个示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM