c++ - 对象动态数组 Sans Vector 类

标签 c++ dynamic-arrays

我正在为我的暑期 OO 类(class)做家庭作业,我们需要编写两个类(class)。一个称为 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 类。这是怎么做到的?

这是我的“注册”“.h”

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;

};

最佳答案

在 Register 类中,您只需要一个 Sale 对象数组,以及一个用于记住销售额的项目计数器。

例如,如果注册表中有 10 个项目,您需要这样做:

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

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

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;

关于c++ - 对象动态数组 Sans Vector 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11149711/

相关文章:

c++ - 在类中使用全局变量作为数组大小

c - C 中的三角数组

c++ - 将字符串文件存储到动态数组中

c++ - 返回地址是否确保非 NULL 返回值?

c++ - 如何检查链表是否为空

在触发操作中使用 system() 时,C++ QT QFileDialog 不会关闭

c++ - 没有名为_M_impl的成员或方法,如何使用pvector打印用clang++和libc++编译的C++的STL vector ,

c++ - 暴力破解不同输入导致程序崩溃的策略是什么?

c++ - C++底漆动态数组的初始化程序数量超过了大小

java - 如何将文件数组值存储到另一个文件数组中