invalid initialization of non-const 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 ) .

:-)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值