1. 程式人生 > >C++陣列的引用—防止陣列退化

C++陣列的引用—防止陣列退化

在c語言中,陣列作為函式引數時,實際上陣列已經退化為指標使用。
下面這三種用法是等價的:

int f1(int apples[]);
int f1(int apples[10]);
int f1(int* apples);

這樣一來,在f1中是無法知道陣列的大小的,開發者必須提前知道陣列大小。

C++中定義了陣列的引用(例如,int (&a)[2]),可以有效的防止陣列退化。
也就是,陣列作為函式引數傳遞過去後,仍然是一個數組。

舉例說明其用法

#include <iostream>
using namespace std;

int f1(int (&a)[6
]) { int count = 0; for(int i=0; i < 6; i++) { count += a[i]; } return count; } int main() { int apples[6] = {2,3,4,5,6,7}; int count = f1(apples); cout<<"count:"<<count<<endl; return 0; }

如果將

int apples[6] = {2,3,4,5,6,7};

改為

int apples[5] = {2,3,4,5,6};

編譯時將報錯

$ g++ array_ref.cpp -o array_ref
array_ref.cpp: In functionint main()’:
array_ref.cpp:24: error: invalid initialization of reference of typeint (&)[6]’ from expression of typeint [5]’
array_ref.cpp:7: error: in
passing argument 1 ofint f1(int (&)[6])’

說明編譯時將進行陣列長度的檢查。

參考

另外不可以定義引用的陣列array of reference。

想定義類似這種
string& array[6] = {};
編譯時報錯
error: declaration of ‘array’ as array of references

There shall be no references to references, no arrays of references, and no pointers to references.

References are not objects. They don’t have storage of their own, they just reference existing objects. For this reason it doesn’t make sense to have arrays of references.