【问题标题】:Reference to array of struct引用结构数组
【发布时间】:2016-11-05 14:46:39
【问题描述】:

我正在学习 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]”转换为“学生 &”

【问题讨论】:

  • 通讯录类型不是student,而是student[100]。而且您不想学习对数组进行引用。只需使用指针/迭代器。

标签: c++ arrays visual-c++ struct


【解决方案1】:

是的,这是可能的。它必须是正确类型的引用。一个学生不是由 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

【讨论】:

    【解决方案2】:

    引用的类型必须与它所引用的相匹配。对单个学生的引用不能引用由 100 个学生组成的数组。您的选择包括:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 2015-03-23
      • 2012-08-06
      相关资源
      最近更新 更多