第10讲对象数组和指针及对象 作为函数参数 教学目的与要求: 了解对象的综合使用。 掌握对象数组和对象指针的使用及对象作为函数参数。 教学内容提要: 1、对象数组; 2、与对象有关指针; 3、对象作为函数参数 教学重点:对象数组、对象指针。 教学难点:对象数组、对象指针 教学进度:P74~P84 教学过程
•教学目的与要求: 了解对象的综合使用。 掌握对象数组和对象指针的使用及对象作为函数参数。 •教学内容提要: 1、 对象数组; 2、与对象有关指针; 3、对象作为函数参数 教学重点:对象数组、对象指针。 •教学难点:对象数组、对象指针。 •教学进度:P74~P84 •教学过程: 第 10 讲 对象数组和指针及对象 作为函数参数
(101对象数组 L声明 类名数组名L素个数] 访问方法: 数组名下标]成员名 3.对象数组的初始化: 口数组中每一个元素对象被创建时,系统都会调用类构造 函数初始化该对象。 口通过初始化列表赋值。 例 Point A2=(Point(1, 2), Point(3, 4); 口如果没有为数组元素指定显式初始值,数组元素便使用 缺省值初始化(调用缺省构造函数)
数组名[下标] . 成员名 1. 声明: 2. 访问方法: 类名 数组名[元素个数]; 3. 对象数组的初始化: 数组中每一个元素对象被创建时,系统都会调用类构造 函数初始化该对象。 通过初始化列表赋值。 例: Point A[2]={Point(1,2),Point(3,4)}; 如果没有为数组元素指定显式初始值,数组元素便使用 缺省值初始化(调用缺省构造函数)。 【10.1 对象数组】
4数组元素所属类的构造函数: 口不声明构造函数,则采用缺省构造函数。 口各元素对象的初值要求为相同的值时,可以声明具有 缺省形参值的构造函数。 Point: Point(int x=0, int y=0) {x=x;Y=y;} Point objl4l 0各元素对象的初值要求为不同的值时,需要声明带形 参(无缺省值)的构造函数。 Point: Point(int x, int y) {X-x;Y=y;} Point obj3: //error Piont obj3=Point(1, 2), Point(3, 4), Point(5,6)) 当数组中每一个对象被删除时,系统都要调用一次析 构函数
不声明构造函数,则采用缺省构造函数。 各元素对象的初值要求为相同的值时,可以声明具有 缺省形参值的构造函数。 Point::Point(int x=0,int y=0) { X=x; Y=y;} Point obj[4]; 各元素对象的初值要求为不同的值时,需要声明带形 参(无缺省值)的构造函数。 Point::Point(int x,int y) { X=x; Y=y;} Point obj[3];//error Piont obj[3]={Point(1,2), Point(3,4), Point(5,6)} 当数组中每一个对象被删除时,系统都要调用一次析 构函数。 4.数组元素所属类的构造函数:
5对象组应用举例: 例10.1 #includesiostream. h> Location: Location(int xx, int yy class location public Y Location ( cout<< Constructor Location(int xx, int yy) cLocation() called. <<endl: void Move(int x, int y); int getx return Locatuon: Location int GetY() return Y private: int XY couteapestructor called s <<endl: Location: Location ( {x=Y=0; void Location: Move(int x, int y cout<< Default Constructor called. <<endl: XEX
#include<iostream.h> class Location { public: Location( ); Location(int xx,int yy); ~Location( ); void Move(int x,int y); int GetX( ) {return X;} int GetY( ) {return Y;} private: int X,Y; }; Location::Location() { X=Y=0; cout<<"Default Constructor called."<<endl; } Location::Location(int xx,int yy) { X=xx; Y=yy; cout<< "Constructor called."<<endl; } Locatuon::~Location() { cout<<"Destructor called.“ <<endl; } void Location::Move(int x,int y) { X=x; Y=y; } 例 10.1 5.对象组应用举例:
int main ( cout<<Entering main, <<endl; Location a2= Location(1, 3), Location (4, 5); for(int i=0; i<2; i++) A[i.Move(i+10,+20); cout<<!Exiting main. <<endl return 0: Entering main Constructor called Constructor called Exiting g Destructor called Destructor called
Entering main... Constructor called. Constructor called. Exiting main... Destructor called. Destructor called. int main( ) { cout<<"Entering main..."<<endl; Location A[2]={Location(1,3),Location(4,5)}; for(int i=0;i<2;i++) A[i].Move(i+10,i+20); cout<<"Exiting main..."<<endl; return 0; }