错误 C2234:引用数组是非法的
error C2234: arrays of references are illegal
我写了这样的代码:
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[],但我失败了。有效的c>
数组要求其元素是默认可构造的,而引用不是,因此引用数组是非法的。这:
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。
这就是为什么引用数组是非法的。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '