无法演员"派生"到其私人基地" base"

时间:2015-03-04 10:13:27

标签: c++ inheritance

我在尝试创建一个继承自定义纯虚函数的类的类的对象时遇到错误。我不确定是什么问题。我知道我需要覆盖派生类中的纯虚函数,但它不起作用。我只想覆盖我的ProduceItem类中的函数而不是我的Celery类,因为我希望Celery类从ProduceItem继承重写的方法。

在Main:

    GroceryItem *cel = new Celery(1.5); //Cannot cast 'Celery' to its private base class GroceryItem


    class GroceryItem
    {
    public:
        virtual double GetPrice() = 0;
        virtual double GetWeight() = 0;
        virtual std::string GetDescription() = 0;

    protected:
        double price;
        double weight;
        std::string description;

    };

ProduceItem头文件:

#include "GroceryItem.h"

class ProduceItem : public GroceryItem
{
public:
    ProduceItem(double costPerPound);
    double GetCost();
    double GetWeight();
    double GetPrice();
    std::string GetDescription();
protected:
    double costPerPound;
};

ProduceItem.cpp文件:

#include <stdio.h>
#include "ProduceItem.h"
ProduceItem::ProduceItem(double costPerPound)
{
    price = costPerPound * weight;
}

double ProduceItem::GetCost()
{
    return costPerPound * weight;
}

double ProduceItem::GetWeight()
{
    return weight;
}

double ProduceItem::GetPrice()
{
    return price;
}

std::string ProduceItem::GetDescription()
{
    return description;
}

Celery头文件:

#ifndef Lab16_Celery_h
#define Lab16_Celery_h
#include "ProduceItem.h"

class Celery : ProduceItem
{
public:
    Celery(double weight);
    double GetWeight();
    double GetPrice();
    std::string GetDescription();

};

#endif

Celery.cpp文件:

#include <stdio.h>
#include "Celery.h"

Celery::Celery(double weight) : ProduceItem(0.79)
{
    ProduceItem::weight = weight;
    description = std::string("Celery");
}

2 个答案:

答案 0 :(得分:27)

您在这里使用私有继承:class Celery : ProduceItemclass es的默认继承级别为private

将其更改为class Celery : public ProduceItem

请注意,当您删除该指针时,由于您没有虚拟析构函数,因此会泄漏内存。只需将类似的定义添加到您的类中:

virtual ~GroceryItem() {}

答案 1 :(得分:4)

默认情况下,类的继承是私有的。通常,在您的情况下,您需要公共继承。所以:

class Celery : public ProduceItem

类似于class ProduceItem

请注意,对于结构,默认情况下继承是公共的(如果需要,可以说struct Foo : private Bar)。