类型为"短整型 (&)"的引用初始化无效

invalid initialization of reference of type ‘short int (&)

本文关键字:引用 初始化 无效 短整型 类型      更新时间:2023-10-16

我正在尝试将数组传递给函数,但出现此奇怪错误

const int size = 2;
void foo(short (&a)[size]){
  cout << a;
}
void testSequence(short a[size]){
  foo(a);
}

错误:从类型为"short int*"的表达式初始化类型为"short int (&([4]"的引用无效

当你声明这样的函数参数

short a[size]

您声明的是指针,而不是数组:

[dcl.fct] 确定后 每个参数的类型,任何类型为"T 数组"或函数类型 T 的参数都调整为"指向 T 的指针"。

foo(short (&a)[size])需要引用大小为 size 的数组。指针不能转换为指针。

声明

void testSequence(short a[size]);

void testSequence(short a[]);

这与

void testSequence(short* a);

因此,呼吁

foo(a); 

从函数无效。

为了能够使用

foo(a);

您必须使用:

void testSequence(short (&a)[size]){
  foo(a);
}

该行

cout << a;

foo也是不对的。<<运算符没有重载,允许将int数组的引用写入cout。您可以使用:

for ( size_t i = 0; i < size; ++i )
{
   std::cout << a[i] << std::endl;
}