0

我正在为我的暑期 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在我们的成员数据中包含一个动态的对象数组。

所以我的两个问题是:

  • 我是否需要从我的Sale班级继承到我的Register班级(如果需要,如何)?
  • 我可以有一个动态数组的通用示例吗?

编辑:我们不能使用向量。

4

3 回答 3

3

不需要继承。一个通用的例子:

std::vector<Sale> sales;

一定要喜欢模板。

于 2012-06-22T02:06:58.683 回答
2

不,在这种情况下继承不合适。您可能希望将销售数量和数组大小作为类中的字段来跟踪Register。类定义将包括这个

class Register{
    private:
        int numSales;
        int arraySize;
        Sale* sales;
    public:
        Register();
        ~Register();
        void MakeSale(Sale);        
};

Register::Register(){
    numSales = 0;
    arraySize = 5;
    sales = new Sale[arraySize];
}
void Register::MakeSale(Sale s){
    if(numSales == arraySize){
        arraySize += 5;
        Sale * tempArray = new Sale[arraySize];
        memcpy(tempArray, sales, numSales * sizeof(Sale));
        delete [] sales;
        sales = tempArray;
    }
    sales[numSales] = s;
    ++numSales;
}

Register::~Register()
{
    delete [] sales;
}

这不包括边界检查或您在进行销售时需要做的任何其他事情,但希望这会有所帮助。

于 2012-06-22T14:55:34.420 回答
0

如果您不能使用向量,那么您可以使用std::list. 您确实应该尽可能多地使用标准容器 - 任何家庭推出的解决方案都可能是劣质的。标准库经过了广泛的优化和测试——当你有比重新发明轮子更好的事情要做时,你真的觉得有必要进行同样的投资吗?

std::list不应分配超出必要的空间。但是,它有一些严重的局限性。向量和其他形式的动态数组是连续的这一事实带来了很大的性能优势。

不能使用向量似乎是一个非常随意的限制。他们分配的空间超出了必要的事实是一个特性,而不是一个错误。它允许容器摊销重新分配中涉及的昂贵的复制和/或移动操作。智能向量实现应该检查内存不足的情况并优雅地处理这些情况。如果没有,您应该将补丁提交到您的标准库实现或移至新的。但是在没有解释的情况下施加任意约束,例如:

此数组中未使用的插槽数不应超过 5 个(即分配的空间数最多可能比实际填充真实数据的插槽数大 5 个)。

是不好的做法。数字五是从哪里来的?这甚至不是二的幂!如果您想使用 破解此限制std::vector::reserve,那可能是您最好的选择。但是,所有这些簿记都不应该需要完成。

而且,与其他人一致:继承不是你想要的。

于 2012-06-22T15:11:18.670 回答