【问题标题】:Cannot cast "derived" to its private base class "base" [duplicate]无法将“派生”转换为其私有基类“基”[重复]
【发布时间】:2015-03-04 10:13:26
【问题描述】:

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

【问题讨论】:

  • 也缺少虚拟析构函数
  • 不是重复的 IMO,在另一个线程中他实际上想要私有继承,但在这种情况下它意味着是公共继承
  • 我同意这不是重复的。

标签: c++ inheritance


【解决方案1】:

您在此处使用私有继承:class Celery : ProduceItemclasses 的默认继承级别是private

改成class Celery : public ProduceItem

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

virtual ~GroceryItem() {}

【讨论】:

    【解决方案2】:

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

    class Celery : public ProduceItem
    

    class ProduceItem 上也类似。

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

    【讨论】:

      猜你喜欢
      • 2012-12-06
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 2013-11-17
      相关资源
      最近更新 更多