无法将"派生"转换为其私有基类"base"

use*_*729 19 c++ inheritance

我在尝试创建一个从一个继承自定义纯虚函数的类的类继承的对象时遇到错误.我不确定是什么问题.我知道我需要覆盖派生类中的纯虚函数,但它不起作用.我只想覆盖我的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;

    };
Run Code Online (Sandbox Code Playgroud)

ProduceItem头文件:

#include "GroceryItem.h"

class ProduceItem : public GroceryItem
{
public:
    ProduceItem(double costPerPound);
    double GetCost();
    double GetWeight();
    double GetPrice();
    std::string GetDescription();
protected:
    double costPerPound;
};
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

芹菜头文件:

#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
Run Code Online (Sandbox Code Playgroud)

Celery.cpp文件:

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

Celery::Celery(double weight) : ProduceItem(0.79)
{
    ProduceItem::weight = weight;
    description = std::string("Celery");
}
Run Code Online (Sandbox Code Playgroud)

Tar*_*ama 33

你在这里使用私有继承:class Celery : ProduceItem.classes 的默认继承级别是private.

将其更改为 class Celery : public ProduceItem

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

virtual ~GroceryItem() {}
Run Code Online (Sandbox Code Playgroud)


Joh*_*nck 7

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

class Celery : public ProduceItem
Run Code Online (Sandbox Code Playgroud)

和类似的class ProduceItem

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