下面隨筆給出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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/262762.html
標籤:C++
上一篇:C++陣列的存盤與初始化
