C++ 对象数组
一、为什么对象可以有数组
类是一种特殊的数据类型,它当然是C++合法的类型,自然就可以定义对象数组。
二、何为对象数组
在一个对象数组中各个元素都是同类对象,
例如:一个班级有50个学生,每个学生具有学号,年龄、成绩等属性,可以为这个班建立一个学生数组,数组包括了50个元素,每个元素都是一个学生对象。
三、如何建立对象数组
float score[50]; //模仿内置类型Student st[50];
类Student建立这样的构造函数:
Student::Student(int=1001,int=20,int=98);
如果构造函数有多个参数,规则要求:在等号后的花括号中为每个对象分别写出构造函数并指定实参。
全体实例:
Student st[3]=
{ <span style="white-space:pre"> </span>Student(1001,21,95), <span style="white-space:pre"> </span>Student(1002,19,65), <span style="white-space:pre"> </span>Student(1003,15,100) //之前的每个后面都有逗号,最后一个后面什么都没有 }; // 不要忘记分号;四、综合实例
/************************************************************ *版权所有 (C) http://blog.csdn.net/chentaowangyuanyuan * * 文件名称: 对象数组 * 文件标识: 无 * 内容摘要: 创建对象数组,分别求对象数组元素体积 * 当前版本: 1.0 * 作 者: 陈涛 * 完成日期: 2015-07 * ***************************************************************/ #include "stdafx.h" #include "iostream" using namespace std; class TBox { public: TBox(double l = 0, double w = 0, double h = 0) :length(l), width(w), heigth(h){} double Volume() const; private: double length, width, heigth; }; double TBox::Volume() const { return length*width*heigth; } int main() { // 为了数字好算用整数代替实数 TBox box[3] = { TBox(10, 20, 30), TBox(20, 30, 40), TBox(30, 40, 50) }; cout << "box[0]的体积为" << box[0].Volume() << endl; cout << "box[1]的体积为" << box[1].Volume() << endl; cout << "box[2]的体积为" << box[2].Volume() << endl; return 0; }结果如下:
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了