对结构数组的引用
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 '初始化':无法从'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
中可以看到一个这样的例子。
相关文章:
- 关于引用数组位置的问题
- 使用指针交换而不引用数组C++
- 对于Boost.Propertytree,有没有办法使用JSON点表示法来引用数组元素?
- 如何在递归函数中调用引用数组?
- 动态指针引用数组由三元运算符返回值,但有异常
- 为什么没有 std::string 构造函数来引用数组
- 指针/引用数组
- 错误 C2234:引用数组是非法的
- 引用数组的方法
- 通过引用数组值进行交换
- 引用数组涉及的技术问题
- 引用数组的函数调用
- 从其他类中的类引用数组
- 如何使用变量名称引用数组位置
- 在 OpenGL 中呈现三角形结构引用数组
- 如何取消引用数组元素(C++)
- c++引用数组数组(指针到指针?)
- 指向指针的指针如何能够引用数组
- C++取消引用数组
- c++中引用数组中对象的共享指针