C++入门经典-例7.9-对象数组,批量化生产
1:在数组内容中我们了解到,数组是通过指针分配到的一段额定大小的内容。同样,数组也可以包含对象。声明对象数组的形式如下:
box boxArray[5];
box boxArray2[2]={box(1,1,1),box(2,2,2)};
box boxArray3[3]={3,styleBox};
值得注意的是,第一种申请对象数组的方法必须保证类中含有默认的够好函数,否则编译器将会报错。同样,可以通过对象指针申请动态数组。例如:
box* box;
pbox=new box[n];//n为整数
同时需要确认box中含有默认构造函数。
2:代码如下:
(1)box.h
class box{ public: //类成员变量 float m_lenth; //长 float m_width; //宽 float m_hight; //高 int Number; //流水线编号 //类成员函数 box(float lenth,float width,float hight); box(); bool Compare(const box b) const;///第一,不希望参数box b改变,第二,不希望引用此函数来改变某一个对象 void ToCheck(); //显示当前盒子的规格 void Rebuild(float lenth,float width,float hight); //重新定义长 宽 高 };
(2)box.cpp
#include "stdafx.h" #include <iostream> #include "box.h" using std::cout; using std::endl; box::box() { m_lenth =1.000f;//f是定义为浮点数类型的意思 m_width = 1.000f; m_hight = 1.000f; cout<<"制作的盒子长:"<<m_lenth<<"宽:"<<m_width<<"高:"<<m_hight<<endl; } box::box(float lenth,float width,float hight) { m_lenth = lenth; m_width = width; m_hight = hight; cout<<"定制作的盒子长:"<<lenth<<"宽:"<<width<<"高:"<<hight<<endl; } bool box::Compare(const box b) const//参见const对象的内容 { return (m_lenth == b.m_lenth)&(m_width == b.m_width)&(m_hight == b.m_hight); } void box::ToCheck()//显示当前盒子的规格 { cout<<"本盒子现在长:"<<m_lenth<<"宽:"<<m_width<<"高:"<<m_hight<<endl; } void box::Rebuild(float lenth,float width,float hight)//重新定义长 宽 高 { m_lenth = lenth; m_width = width; m_hight = hight; }