下面隨筆給出C++對象數組的要點。
對象數組的定義與訪問
-
定義對象數組
類名 數組名[元素個數];
-
訪問對象數組元素
通過下標訪問
數組名[下標].成員名
對象數組初始化
-
數組中每一個元素對象被創建時,系統都會調用類構造函數初始化該對象。
-
通過初始化列表賦值。
例:Point a[2]={Point(1,2),Point(3,4)};
-
如果沒有為數組元素指定顯式初始值,數組元素便使用默認值初始化(調用默認構造函數)。
數組元素所屬類的構造函數
-
元素所屬的類不聲明構造函數,則采用默認構造函數。
-
各元素對象的初值要求為相同的值時,可以聲明具有默認形參值的構造函數。
-
各元素對象的初值要求為不同的值時,需要聲明帶形參的構造函數。
-
當數組中每一個對象被刪除時,系統都要調用一次析構函數。
例 對象數組應用舉例
1 //Point.h 2 3 #ifndef _POINT_H 4 5 #define _POINT_H 6 7 class Point { //類的定義 8 9 public: //外部接口 10 11 Point(); 12 13 Point(int x, int y); 14 15 ~Point(); 16 17 void move(int newX,int newY); 18 19 int getX() const { return x; } 20 21 int getY() const { return y; } 22 23 static void showCount(); //靜態函數成員 24 25 private: //私有數據成員 26 27 int x, y; 28 29 }; 30 31 #endif //_POINT_H
1 //Point.cpp 2 3 #include <iostream> 4 5 #include "Point.h" 6 7 using namespace std; 8 9 Point::Point() : x(0), y(0) { 10 11 cout << "Default Constructor called." << endl; 12 13 } 14 15 Point::Point(int x, int y) : x(x), y(y) { 16 17 cout << "Constructor called." << endl; 18 19 } 20 21 Point::~Point() { 22 23 cout << "Destructor called." << endl; 24 25 } 26 27 void Point::move(int newX,int newY) { 28 29 cout << "Moving the point to (" << newX << ", " << newY << ")" << endl; 30 31 x = newX; 32 33 y = newY; 34 35 }
1 //sample.cpp 2 3 #include "Point.h" 4 5 #include <iostream> 6 7 using namespace std; 8 9 int main() { 10 11 cout << "Entering main..." << endl; 12 13 Point a[2]; 14 15 for(int i = 0; i < 2; i++) 16 17 a[i].move(i + 10, i + 20); 18 19 cout << "Exiting main..." << endl; 20 21 return 0; 22 23 }
1 運行結果: 2 Entering main... 3 Default Constructor called. 4 Default Constructor called. 5 Moving the point to (10,20) 6 Moving the point to (11,21) 7 Exiting main... 8 Destructor called. 9 Destructor called.