1. 程式人生 > >C++——二維數組和對象數組

C++——二維數組和對象數組

按順序 keyword ring -c 對象 += a20 所有 默認構造函數

6.3 二維數組的聲明和引用

聲明:數據類型 標識符[常量表達式1][常量表達式2]int a[3][4];

表示a為整型二維數組,其中第一維有3個下標(0~2),第二維有4個下標(0~3),數組元素12個,可以用來存放3行4列的整型數據表格。可以理解為:

a[0]——a 00 a01 a02 a03

a[1]——a10 a11 a12 a13
a[2]——a20 a21 a22 a23存儲順序是按行存儲a00 a01 a02 a03 a10 a11 a12 a13 a20 a21 a22 a23

引用的時候下標不可越界,例如b[1][5]=a[2][3]/2,不可以寫成a[3][4],否則發生錯誤。

二維數組的初始化

將所有數據寫在一個{}內,按順序賦值,例如:static int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};

分行給二維數組賦初值,例如:static int a[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};

可以對部分元素賦初值,例如:static int a[3][4]={{1},{0,6},{0,0,11}};

數組作為函數參數

數組元素作為實參,與單個變量一樣。

數組名作為參數,形實參數都應是數組名,類型要一樣,傳送的是數組首地址。對形參數組的改變會直接影響到實參數組。

#include <iostream>

using namespace std;

void RowSum(int A[][4], int nrow)    //計算二維數組A每行元素的值的和,nrow是行數

{        for (int i = 0; i < nrow; i++)

         {

                   for(int j = 1; j < 4; j++)

                         A[i][0] += A[i][j];

         }

}

int main()   //主函數

{

         int Table[3][4] = {{1,2,3,4},{2,3,4,5},{3,4,5,6}};     //聲明並初始化數組

         for (int i = 0; i < 3; i++)       //輸出數組元素

         {

                   for (int j = 0; j < 4; j++)

                         cout << Table[i][j] << "   ";

                   cout << endl;

         }

         RowSum(Table,3);        //調用子函數,計算各行和

         for (i = 0; i < 3; i++)   //輸出計算結果

         {

               cout << "Sum of row " << i << " is " <<Table[i][0]<< endl;

         }

}

  

運行結果:

1 2 3 4

2 3 4 5

3 4 5 6

Sum of row 0 is 10

Sum of row 1 is 14

Sum of row 2 is 18

10 14 18

6.3 對象數組

聲明:類名 數組名[元素個數]

訪問方法:通過下標訪問 數組名[下標].成員名

初始化:數組中每一個元素對象被創建時,系統都會調用類構造函數初始化該對象。

通過初始化列表賦值:point A[2]={point(1,2),point(3,4)};

如果沒有為數組顯示指定初始值,數組元素使用默認值初始化(調用默認構造函數)

//Point.h

#if !defined(_POINT_H)

#define _POINT_H

class Point

{   public:

       Point();

       Point(int xx,int yy);

       ~Point();

       void Move(int x,int y);

       int GetX() {return X;}

       int GetY() {return Y;}

  private:

       int  X,Y;

};

#endif

//Point.cpp

#include<iostream>

using namespace std;

#include "Point.h"

Point::Point()

{   X=Y=0;

     cout<<"Default Constructor called."<<endl;

}

Point::Point(int xx,int yy)

{   X=xx;

     Y=yy;

     cout<< "Constructor called."<<endl;

}

Point ::~Point()

{  cout<<"Destructor called."<<endl;  }

void Point ::Move(int x,int y)

{      X=x;    Y=y;  }

#include<iostream>

#include "Point.h"

using namespace std;

int main()

{   cout<<"Entering main..."<<endl;

   Point A[2];

   for(int i=0;i<2;i++)

     A[i].Move(i+10,i+20);

   cout<<"Exiting main..."<<endl;

   return 0;

}

C++——二維數組和對象數組