[英]Could not convert from <brace-enclosed initializer list> to int(*) array
I am very new to C++, and would like some help with this error I keep getting. 我是C ++的新手,我希望得到一些有关此错误的帮助。
#include <iostream>
#include <string>
using namespace std;
void print (int test[2][2]= {{1,2},{3,4}})
{
cout << test[0][0] << endl;
cout << test[1][0] << endl;
}
int main()
{
print();
return 0;
}
The error is: could not convert '{{1, 2}, {3, 4}}' from '' to 'int (*)[2]'| 错误是:无法将'{{1,2},{3,4}}'从'转换为'int(*)[2]'|
I am a beginner in C++ and am still learning. 我是C ++的初学者,但仍在学习中。
Function parameters declared as arrays are adjusted implicitly to pointers to their first elements. 声明为数组的函数参数会隐式调整为指向其第一个元素的指针。
So the function declaration actually looks like 所以函数声明实际上看起来像
void print ( int ( *test )[2] = { { 1, 2 }, { 3, 4 } } );
and the pointer may not be initialized such a way because it is a scalar object. 并且指针可能不是这样初始化的,因为它是标量对象。
In fact these function declarations 实际上这些函数声明
void print( int test[10][2] );
void print( int test[2][2] );
void print( int test[][2] );
void print( int ( *test )[2] );
are equivalent and declare the same one function. 等价并声明相同的一个函数。
However you could define the parameter as a reference to an array. 但是,您可以将参数定义为对数组的引用。 In this case you would get the expected result. 在这种情况下,您将获得预期的结果。 For example 例如
#include <iostream>
void print ( const int ( &test )[2][2] = { { 1, 2 }, { 3, 4 } } )
{
std::cout << test[0][0] << std::endl;
std::cout << test[1][0] << std::endl;
}
int main()
{
print();
int a[2][2] = { { 5, 6 }, { 7, 8 } };
print( a );
}
The program output is 程序输出为
1
3
5
7
There is an easy work around: 有一个简单的解决方法:
void print (int test[2][2])
{
cout << test[0][0] << endl;
cout << test[1][0] << endl;
}
void print ()
{
int test[2][2] = {{1,2},{3,4}};
print(test);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.