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

:-)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM