我正在为我的暑期 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/