一.定义
数组中的每一个元素都是类的对象
二.声明一个一维对象数组的一般形式
类名 数组名[常量表达式];
三.引用对象数组元素的公有成员
数组名[下标].成员名;
四.对象数组的初始化
调用构造函数对每个元素初始化
如: Box a[3]={Box(10,12,15),Box(15,16,17),Box(16,20,26)};
五.例题
#include <iostream>
using namespace std;
class Box
{private:
int height;
int width;
int length;
public:
Box(int h=10,int w=12,int len=15):
height(h),width(w),length(len){ }
int volume( );
};
int Box∷volume( )
{return(height*width*length);
}
int main( )
{ Box a[3]={
Box(10,12,15),
Box(15,18,20),
Box(16,20,26) };
cout<<a[0].volume( )<<endl;
cout<<a[1].volume( )<<endl;
cout<<a[2].volume( )<<endl;
}
#include <iostream>
#include <cstring>
using namespace std;
class CStudent
{
private:
int number;
char name[10];
int age;
public:
CStudent(int xh=0, char *xm="Noname", int a=18);
void setStudent(int xh=0, char *xm="Noname", int a=18);
int GetAge();
};
CStudent::CStudent(int xh, char *xm, int a)
{ number = xh;
strcpy(name, xm);
age = a; }
void CStudent::setStudent(int xh, char *xm, int a)
{ number = xh;
strcpy(name, xm);
age = a; }
int CStudent::GetAge()
{ return age;}
int main()
{
int sum=0;
CStudent s[8] = { CStudent(10001, "AAAAAA", 20),
CStudent(10002, "BBBBBB",22 ),
CStudent( ), CStudent( ),
CStudent(10005, "EEEEEE",18 )
};
s[2].setStudent(10003, "CCCCCC",24 );
s[3].setStudent(10004, "DDDDDD",21 );
s[5].setStudent(10006, "FFFFFFF",23 );
s[6].setStudent(10007, "GGGGGG",20 );
for(int i=0; i<6; i++)
{ sum += s[i].GetAge(); }
cout << sum/6 << endl;
return 0;
}
运行结果
21