动态数组对象无矢量类

时间:2012-06-22 03:12:38

标签: c++ dynamic-arrays

我正在为我的夏季OO班做一个家庭作业,我们需要写两个班。一个称为Sale,另一个称为Register。我写了Sale课;这是.h文件:

enum ItemType {BOOK, DVD, SOFTWARE, CREDIT};

class Sale
{
public:
    Sale();         // default constructor, 
            // sets numerical member data to 0

    void MakeSale(ItemType x, double amt);  

    ItemType Item();        // Returns the type of item in the sale
    double Price();     // Returns the price of the sale
    double Tax();       // Returns the amount of tax on the sale
    double Total();     // Returns the total price of the sale
    void Display();     // outputs sale info 

private:
    double price;   // price of item or amount of credit
    double tax;     // amount of sales tax 
    double total;   // final price once tax is added in.
    ItemType item;  // transaction type
};

对于Register类,我们需要在成员数据中包含动态数组的Sale个对象。我们不能使用vector类。这是怎么做到的?

这是我的'注册''。''

class Register{
public:

Register(int ident, int amount);
~Register();
int GetID(){return identification;}
int GetAmount(){return amountMoney;}
void RingUpSale(ItemType item, int basePrice);
void ShowLast();
void ShowAll();
void Cancel();
int SalesTax(int n);

private:

int identification;
int amountMoney;

};

1 个答案:

答案 0 :(得分:1)

Register类中所需要的只是一个Sale对象数组,还有一个项目计数器,用于记住销售量。

例如,如果注册表中有10个项目,则需要执行此操作:

int saleCount = 10;
Sale[] saleList = new Sale[saleCount];

要使数组动态化,您需要在每次销售计数增加时创建一个新的Sale数组,并将saleList中的所有项目复制到新的销售列表中。最后在最后添加新的销售。

saleCount++;
Sale[] newSaleList = new Sale[saleCount];
//copy all the old sale items into the new list.
for (int i=0; i<saleList.length; i++){
  newSaleList[i] = saleList[i];
}
//add the new sale at the end of the new array
newSaleList[saleCount-1] = newSale;
//set the saleList array as the new array
saleList = newSaleList;
相关问题