天天看點

c++ const引用 和 引用數組總結const 和 資料類型可以交換跟指針一樣,const修飾的是右邊的變量常引用可以指向常量,當做常量使用常引用 指向 表達式常引用作為函數形參可以接收 const類型 和 非 const類型,常引用 和 非const引用可以構成函數重載指針形參的const和非const也能構成重載,跟const 引用一樣普通的形參變量 const和 非const 無法構成重載引用數組的2種格式:

目錄

  • const 和 資料類型可以交換
  • 跟指針一樣,const修飾的是右邊的變量
  • 常引用可以指向常量,當做常量使用
  • 常引用 指向 表達式
  • 常引用作為函數形參可以接收 const類型 和 非 const類型,常引用 和 非const引用可以構成函數重載
  • 指針形參的const和非const也能構成重載,跟const 引用一樣
  • 普通的形參變量 const和 非const 無法構成重載
  • 引用數組的2種格式:

const 引用,又叫常引用,引用的本質是指針,是以很多東西都是相通的.

const 和 資料類型可以交換

下面代碼 int const 和 const int作用一樣

int a = 1;
 int const &ref = a;    
 const int &ref = a; 

           

跟指針一樣,const修飾的是右邊的變量

int const 和 const int可以交換,是以修飾的是int,表示int是不能改變的

int a = 1;
    int const &ref = a;
//    ref = 10;//錯誤,常引用不能修改值
    
    const int &ref2 = a; //const int 等價于 int const,因為const 和資料類型可以交換
//    ref2 = 20;
           

常引用可以指向常量,當做常量使用

作用可以看做是 swift中的let width = 100

如下

int const &ref3 = 30; //當做常量使用,因為30是不能改變的,是以 常引用 ref3可以指向30
    cout << ref3 <<endl;

           

常引用 指向 表達式

常引用右邊可以是個表達式,例如一個函數,函數傳回值需要是常量const

int sum(){
    return 10;
}
void main(int argc, const char * argv[]) {
    const int &ref4 = sum();//因為sum的傳回值是常量,是以用常引用可以使用
}
           

常引用作為函數形參可以接收 const類型 和 非 const類型,常引用 和 非const引用可以構成函數重載

int sum2(const int &a,const int &b){
   cout<< " sum2(const int &a,const int &b)"<< endl;
   return a + b;
}
int sum2( int &a,int &b){
   cout<< "sum2( nt &a,int &b)"<< endl;
   return a + b;
}

void main(int argc, const char * argv[]) {  
   int result = sum2(10,20);
   int a1 = 1;
   int a2 = 2;
   int result2 = sum2(a1, a2);//a1,a2都是變量,但是可以可以傳給 const 形參函數
}
           

運作結果:

sum2(const int &a,const int &b)

sum2( nt &a,int &b)

指針形參的const和非const也能構成重載,跟const 引用一樣

void sum3(const int *p1, const int *p2){
    cout << "sum3(const int *p1, const int *p2)" <<endl;
}
void sum3( int *p1,  int *p2){
    cout << " sum3( int *p1,  int *p2)" <<endl;
}
void main(int argc, const char * argv[]) {   
    sum3(&a1, &a2);
    const int *p1 = &a1;
    const int *p2 = &a2;
    sum3(p1, p2);
}
           

普通的形參變量 const和 非const 無法構成重載

void sum4( int a,  int b){
    cout << " sum4( int a,  int b)" <<endl;
}

//但是普通的形參變量 const和 非const 無法構成重載
void sum4( const int a,const  int b){
    cout << " sum4( int a,  int b)" <<endl;
}
//這裡會報錯:Redefinition of 'sum4' 表示重定義了sum4,因為2個sum4不能重載 
 
           

引用數組的2種格式:

  • int (&ref1)[3] = arr;
  • int * const &ref2 = arr;
int arr[] = {1,2,3};
    //數組的引用格式1
    int  (&ref1)[3] = arr;
    ref1[0] = 10;
    
    //數組的引用格式2
    int * const &ref2 = arr;
    ref2[1] = 20;
    
    for (int i = 0 ;i < 3 ; i++){
        cout<< arr[i] << endl;
    }
           

繼續閱讀