C++语言程序设计 对象数组 数 。声明: 类名数组名[元素个数] 组 ·访问方法: 通过下标访问 数组名下标]成员名
C++语言程序设计 21 对象数组 声明: 类名 数组名[元素个数]; 访问方法: 通过下标访问 数组名[下标].成员名 数 组
C++语言程序设计 对象数组初始化 数 数组中每一个元素对象被创建时,系统 都会调用类构造函数初始化该对象。 组·通过初始化列表赋值。 例: Point a[2]={Point (1,2),Point (3,4)} ·如果没有为数组元素指定显式初始值, 数组元素便使用默认值初始化(调用缺 省构造函数)。 22
C++语言程序设计 22 对象数组初始化 数组中每一个元素对象被创建时,系统 都会调用类构造函数初始化该对象。 通过初始化列表赋值。 例: Point a[2]={Point(1,2),Point(3,4)}; 如果没有为数组元素指定显式初始值, 数组元素便使用默认值初始化(调用缺 省构造函数)。 数 组
C++语言程序设计 数组元素所属类的构造数 数·不声明构造函数,则采用缺省构造函数。 ·各元素对象的初值要求为相同的值时, 组 可以声明具有默认形参值的构造函数。 ·各元素对象的初值要求为不同的值时, 需要声明带形参的构造函数。 当数组中每一个对象被删除时,系统都 要调用一次析构函数。 23
C++语言程序设计 23 数组元素所属类的构造函数 不声明构造函数,则采用缺省构造函数。 各元素对象的初值要求为相同的值时, 可以声明具有默认形参值的构造函数。 各元素对象的初值要求为不同的值时, 需要声明带形参的构造函数。 当数组中每一个对象被删除时,系统都 要调用一次析构函数。 数 组
C++语言程序设计 例63对象数组应用举例 //Point.h 数 #ifndef POINT H #define POINT H class Point,{、/类的定义 组 public: /外部接口 Point() Point(int x,int y); Point () void move(int newX,int newY) int getx()const t return x; int gety() const return y; private: 7私有数据成 int x,y; #endif //POINT_H
C++语言程序设计 24 例6-3 对象数组应用举例 //Point.h #ifndef _POINT_H #define _POINT_H class Point { //类的定义 public: //外部接口 Point(); Point(int x, int y); ~Point(); void move(int newX,int newY); int getX() const { return x; } int getY() const { return y; } private: //私有数据成员 int x, y; }; #endif //_POINT_H 数 组
//Point.cpp #include <iostream.〉 #include "Point.h using namespace std; Point:Point(){ x=y=0; cout <<"Default Constructor called."<endl; Point:Point (int x,int y):x(x),y(y){ cout <<Constructor called. <endl; Point:Point(){ cout <"Destructor called."<<endl; void Point:move(int newX,int newY){ 8e既及ov,point to(《nemx<K”,”< ”<<endl; x newX; y newY; 25
//Point.cpp #include <iostream> #include "Point.h" using namespace std; Point::Point() { x = y = 0; cout << "Default Constructor called." << endl; } Point::Point(int x, int y) : x(x), y(y) { cout << "Constructor called." << endl; } Point::~Point() { cout << "Destructor called." << endl; } void Point::move(int newX,int newY) { cout << "Moving the point to (" << newX << ", " << newY << ")" << endl; x = newX; y = newY; } 25