下面随笔给出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.