C++二維數(shù)組初始化相關(guān)應(yīng)用技巧分享
在C++編程語言中,對于數(shù)組的操作是一個(gè)非常基礎(chǔ)而又重要的應(yīng)用技術(shù)。我們在這篇文章中會為大家詳細(xì)介紹C++二維數(shù)組初始化的相關(guān)操作方法,方便大家對這方面的應(yīng)用技術(shù)有所掌握。C++的二維數(shù)組是不能用變量初始化的,像下面的代碼肯定是編譯不通過的:
- int i=5;
- int j=4;
- int a[i][j];
像這樣的代碼肯定是很多C++像我一樣的初學(xué)者的困感,如果數(shù)組是在編譯的階段確定其內(nèi)存位置的,而變量不能作為數(shù)組的維數(shù).下面,用一個(gè)模板類,完成這種C++二維數(shù)組初始化的功能
- template< class T>
- class Array2D{
- private:
- T* pData;
- int dim1;
- int dim2;
- int dim1Index;
- class Array1D{
- private:
- int length;
- T* start;
- public:
- Array1D(T* start,int length):length(length),start(start){}
- T& operator[](int index){
- if(index>length){
- throw out_of_range("數(shù)組第二維數(shù)越界");
- }else{
- return *(start+index);
- }
- }
- };
- public:
- Array2D(int dim1,int dim2){
- this->dim1dim1=dim1;
- this->dim2dim2=dim2;
- int size=dim1*dim2;
- pData=new T[size];
- }
- Array1D operator[](int index){
- return Array1D(pData+index*dim1,dim2);
- }
- void print(){
- for(int i=0;i< dim1;i++){
- for(int j=0;j< dim2;j++){
- cout< < *(pData+dim1*i+j)< < " ";
- }
- cout< < endl;
- }
- }
- };
- int main(){
- int index1=2;
- int index2=2;
- Array2D< int> test(index1,index2);
- test[0][0]=1;
- test[0][1]=2;
- test[1][0]=3;
- test[1][1]=4;
- test.print();
- }
用一個(gè)模板類實(shí)現(xiàn)這個(gè)功能,是C++二維數(shù)組初始化中一個(gè)不錯(cuò)的選擇,但在實(shí)際中,是很少有人這樣寫的,這是在more effective C++給出的方法,目的是為了說明proxy模式,Array1D是作為一個(gè)proxy類存在的。
【編輯推薦】