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); //重新定义长 宽 高
    
};
   
View Code

(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;
}
View Code

(3)main.cpp

// 7.9.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "box.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
bool check(float a,float b,float c)//自定义了一个函数
{
    return (a>0)&(b>0)&(c>0)&(a<100)&(b<100)&(c<100);//如果a,b,c都介于0到100之间就返回1
}
int main()
{
    float lenth;
    float hight;
    float width;
    cout<<"请输入您所需要盒子,长、宽、高"<<endl;
    while(cin>>lenth,cin>>hight,cin>>width,!check(lenth,width,hight))//逗号运算符是指在C语言中,多个表达式可以用逗
    //号分开,其中用逗号分开的表达式的值分别结算,但整个表达式的值是最后一个表达式的值。   
    {
        cout<<"抱歉,你所输入的规格超出我们的制作水平,请重新输入"<<endl;
    }
    const box styleBox(lenth,width,hight);
    cout<<"请输入您的订单个数:"<<endl;
    int count;
    while(cin>>count,!((count>0)&(count<6)))//数字检查
    {
        if(count>5)
        {
            cout<<"抱歉,订单数额超出生产水平,请重新输入"<<endl;
        }
        else{
            cout<<"请确认输入的数值为正数,请重新输入"<<endl;
        }
    }
    box* boxArray ;   //定义了一个指向对象的指针,注意:此种方法要有默认的构造函数,因为上来就会来几个默认的对象,然后赋值
    boxArray = new box[count];  //动态对象数组//通过对象指针申请对象数组//这个数组的名就叫boxarray
    bool bOk = false;
    
        for(int i=0;i<count;i++)
        {
            boxArray[i].Rebuild(lenth,width,hight);
            boxArray[i].ToCheck();
            if(styleBox.Compare(boxArray[i]))
            {
                cout<<"此产品符合规格"<<endl;
            }
        }
        delete []boxArray;//删除类成员时就用这种
        return 0;
}
View Code