对象数组

一.定义

数组中的每一个元素都是类的对象

二.声明一个一维对象数组的一般形式

类名 数组名[常量表达式];

三.引用对象数组元素的公有成员

数组名[下标].成员名;

四.对象数组的初始化

调用构造函数对每个元素初始化
如: 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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值