无法将"derived"强制转换为其私有基类"base"

Cannot cast "derived" to its private base class "base"

本文关键字:基类 base derived 转换      更新时间:2023-10-16

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

主要:

    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;
}

芹菜头文件:

#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");
}

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

更改为class Celery : public ProduceItem

请注意,当您删除该指针时,您将泄漏内存,因为您没有虚拟析构函数。只需在类中添加这样的定义:

virtual ~GroceryItem() {}

默认情况下,类的继承是私有的。通常,在您的情况下,您想要公共继承。因此:

class Celery : public ProduceItem

在CCD_ 5上也是类似的。

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