类型为"短整型 (&)"的引用初始化无效
invalid initialization of reference of type ‘short int (&)
我正在尝试将数组传递给函数,但出现此奇怪错误
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;
}
相关文章:
- C++-模板嵌套类的引用初始化无效
- 在引用初始化中使用已删除的复制构造函数进行复制初始化
- 模板流运算符重载错误:引用初始化无效,与basic_istream和basic_ifstream之间的差异有关
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- 类型为"短整型 (&)"的引用初始化无效
- 引用初始化和常量表达式
- 在Visual Studio 2013中为rvalue引用初始化捕获
- 从大括号括起来的初始值设定项列表进行的Lvalue引用初始化无法编译
- Visual C++ 2015 中右值的非常量引用初始化无效
- 是否可以使用对派生类实例的基类引用初始化派生类引用
- 类型'int&'的引用初始化无效,传递参数 1 时出错
- 引用初始化表单
- 从类型为"int*"的临时引用初始化类型为"int&"的非常量引用无效
- 简单的C++日志记录类-ostream引用初始化
- 错误:类型为"cv::Mat&"的非常量引用初始化无效
- 为什么我收到类型为"const vec&"的引用初始化无效
- 从类型为"char*"的临时引用初始化类型为"char*&"的非常量引用
- 为什么这会发送一个关于引用初始化无效的错误
- 为什么此处不对引用初始化执行复制初始化?
- std::vector不会为多个向量条目创建cv::Mat的新引用——初始化矩阵时,数据会被覆盖