错误 C2234:引用数组是非法的

error C2234: arrays of references are illegal

本文关键字:非法 数组 引用 C2234 错误      更新时间:2023-10-16

我写了这样的代码:

void Print(const int & dataArray[], const int & arraySize) {  // problem 
for(int i = 0; i<arraySize; i++) {
cout << dataArray[i] << " ";
}
cout << endl;
}

在 mian() 函数中:

`
int iArray[14] = { 7, 3, 32, 2, 55, 34, 6, 13, 29, 22, 11, 9, 1, 5 }; 
int numArrays = 14;
Print(iArray, numArrays);
....
`

编译器说引用数组是非法的,为什么是非法的? 我看到<有效的c>,它说建议我们使用const和引用,我只是尝试实现它(我是初学者),我也想知道在void Print(const int dataArray[], const int & arraySize)参数中使用const,并限定arraySize,对吗?(或者它比int arraySize或const int arraySize好得多?),我也想使用const,&to dataArray[],但我失败了。

数组要求其元素是默认可构造的,而引用不是,因此引用数组是非法的。这:

const int & dataArray[]

是一个引用数组。如果你想要一个数组的引用,你需要这个:

const int (&dataArray)[]

从学究上讲,引用数组非法的原因是标准明确禁止它们。

C++03:8.3.2/4

不得引用引用,不得引用数组, 并且没有指向引用的指针。

强调我的。

标准明确禁止引用数组(可能还有更多)的一个原因是数组的索引方式。 假设您执行以下操作:

Gizmo& gizmos[] = {...};
Gizmo&* g3 = &gizmos[2];

这里有几点错误。 首先,你有一个指向引用的指针,这是非法的。 其次,为了计算gizmos[2]编译器必须执行隐式到指针的转换,然后基于该转换进行指针运算。Gizmo&有多大?

根据该标准,参考文献sizeof本身是未指定的。 但是,当sizeof应用于引用时,结果是引用类型的大小。

C++03:5.3.3/2 Sizeof

应用于引用或引用类型时,结果为 引用类型的大小。

尝试运行此代码,看看会发生什么:

#include <iostream>
#include <iomanip>
using namespace std;
struct Gizmo { int n_[100]; };
int main()
{
typedef Gizmo& GR;
size_t n = sizeof(GR);
cout << n << endl;
}

当我在我的计算机(MSVC10、Win7x64)上运行它时,结果是 400。

这就是为什么引用数组是非法的。