被问及以下问题:
using namespace std;
void func( int * &a, int b)
{
for( int i= 0;i<b;i++)
a[i]+=i;
}
int main()
{
int test[ 10]={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 7};
func(test, 4);
cout<< " After assignment, test is "<<endl;
...
}
error: invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
we both know:
int func(int *a, int b); 可以正确运行。
理解其初始意图,想对 int指针 当一个引用 处理。
上面代码的调用处, 可以相当于以下:
{
int y=3;
int &x = y;
int* address_y=&y;
int* &ref_y = address_y;
int array[3] ={1,2,3};
int* address_array= array;
int* &ref_address_array = address_array;
//int* &ref = array;//error , the same effect as func(test,4);
}
{
int test[ 10]={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *temp = test; /* **** 加一变量转换 ****** */
func(temp, 4); /* **** 用变量转换 ****** */
cout<< " After assignment, test is "<<endl;
for( int i = 0;i< 10;i++)
printf( " %d\t ",test[i]);pasting
printf( " \n ");
}
======
后续:找到原因:
quote:"是因为数组名是一个地址常量,非const引用不能引用一个常量。如果把void func(int *&a, int b)改成void func(int *const &a,int b)就可以编译通过。 "
同时解释了为何上述的 int *temp 为何可以,int * temp =test;//转换成 non-const reference , match with func( int * , int ) .
:-)