invalid initialization of nonconst reference of type ‘int*&’ from a temporary of type ‘int*’

被问及以下问题:

#include<iostream> 
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指针 当一个引用 处理。

  实际上,指针与引用没有多少差别。只是调用的时候,指针需要在调用的时候,临时转换一个指针。(we heard that) 。而引用则省去了这个步骤。

  上面代码的调用处, 可以相当于以下:

int main(void) 

{
    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);

} 


  error: invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
  这个重点似乎在于 temporary 。
  而 "临时变量作为非const的引用参数传递" ,编译器不允许的。(ref 2 this) http://blog.baisi.net/?116670/viewspace-4407 
  但如果修改以下这个转换,则可以进行编译通过并运行。
int main() 

    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");
两者区别,我没看出来。test, temp 都是 lvalue 。似乎加一变量 没有了“ 临时 ”的效果。

 ======

后续:找到原因:

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 ) .

:-)

原文地址:https://www.cnblogs.com/no7dw/p/2358210.html