第六章数组指针与字符串
C++语言程序设计
1
本章主要内容
数组
指针
动态存储分配
指针与数组
指针与函数
字符串
2
对象数组
一维数组声明:
类名数组名[元素个数];
数组元素
对象
具有数据成员和成员函数
访问方法:
通过下标访问
数组名[下标].成员名
数组
3
对象数组初始化
数组中每一个元素对象被创建时,系统都会调用类构造函数初始化该对象
通过初始化列表赋值
Point A[2]={Point(1,2),Point(3,4)};
如果没有为数组元素指定显式初始值,数组元素便使用缺省值初始化(调用缺省构造函数)
Point A[2]={Point(1,2)};
数组
4
数组元素所属类的构造函数
不声明构造函数,则采用缺省构造函数
各元素对象的初值要求为相同的值时,可以声明具有缺省形参值的构造函数
各元素对象的初值要求为不同的值时,需要声明带形参(无缺省值)的构造函数
当数组中每一个对象被删除时,系统都要调用一次析构函数
数组
5
例6-5 对象数组应用举例
//
#if !defined(_LOCATION_H)
#define _LOCATION_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;
};
#endif
数组
6
//6-
#include<>
#include ""
Location::Location( )
{ X=Y=0;
cout<<"Default Constructor called."<<endl;
}
Location::Location(int xx,int yy)
{ X=xx;
Y=yy;
cout<< "Constructor called."<<endl;
}
7
Locatuon::~Location( )
{
cout<<"Destructor called."<<endl;
}
void Location::Move(int x,int y)
{
X=x;
Y=y;
}
8
int main( )
{
cout<<"Entering main..."<<endl;
Location A[2];
//Location A[2]={Location(1,2),Location(4,5)};
for(int i=0;i<2;i++)
A[i].Move(i+10,i+20);
cout<<"Exiting main..."<<endl;
return 0;
}
9
运行结果:
Entering main...
Default Constructor called.
Default Constructor called.
Exiting main...
Destructor called.
Destructor called.
10
c++6 来自淘豆网www.taodocs.com转载请标明出处.