【发布时间】:2014-01-06 18:19:09
【问题描述】:
我有一个关于使用引用运算符传递数组的问题。我想编写使用引用运算符传递数组的代码。然后我尝试了
void swap(int &testarray[3]){
// code
}
它给了我错误。它说,
/main.cpp:5: error: declaration of 'testarray' as array of references
但是当我用
更改我的代码时void swap(int (&testarray)[3]){
// code
}
它运行正常。唯一的区别是有括号。
为什么需要括号,int (&testarray)[3] 和 int &testarray[3] 有什么区别
感谢您的帮助。
【问题讨论】:
-
为什么要通过引用传递数组?
-
@Cornstalks 为什么你不想通过引用传递一个数组? @burakim:既然你已经标记了这个 C++11,你可以切换到
std::array<int, 3>并避免这种 C 声明符语法的变幻莫测。 -
@Praetorian: 因为数组不能被赋值,并且已经衰减为指针。
-
@Cornstalks 我看不出不可分配的相关性,您仍然可以分配给单个元素。并且衰减到指针会丢失大小信息,这对于大多数用例来说很不方便。
-
通过引用传递,您可以使用
std::end(testarray)
标签: c++ arrays pass-by-reference