gpt4 book ai didi

c++ - 引用结构数组

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:12 24 4
gpt4 key购买 nike

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

我收到以下错误:

a reference of type "student &" (not const-qualified) cannot be initialized with a value of type "student [100]"
Error C2440 'initializing': cannot convert from 'student [100]' to 'student &'

最佳答案

引用的类型必须与其引用的内容相匹配。对单个学生的引用不能引用 100 名学生的数组。您的选择包括:

// Refer to single student
student &test = addressbook[0];

// Refer to all students
student (&all)[100] = addressbook;
auto &all = addressbook; // equivalent

关于c++ - 引用结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38175057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com