【问题标题】:C++ passing array using reference operatorC++ 使用引用运算符传递数组
【发布时间】: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


【解决方案1】:

void foo(int &testarray[3]) 被解释为void foo((int &)testarray[3]) 由于优先级。并且引用数组是非法的。

void foo(int (&testarray)[3]) 被解释为你想要的。 (3 int 数组的引用)。

void foo(int testarray[3]) 等价于void foo(int testarray[]) 衰减到void foo(int *testarray)。 (整数指针)。

【讨论】:

    【解决方案2】:

    其实这个结构

    int & testarray[3]
    

    定义了一个对整体对象的引用数组。 C++ 标准不允许定义对对象的引用数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-18
      • 2018-12-18
      • 1970-01-01
      • 2019-08-17
      • 2012-07-29
      • 2012-05-13
      • 1970-01-01
      • 2018-09-01
      相关资源
      最近更新 更多