无法将"derived"强制转换为其私有基类"base"
Cannot cast "derived" to its private base class "base"
当我试图创建一个从定义纯虚拟函数的类继承的对象时,遇到了一个错误。我不确定出了什么问题。我知道我需要覆盖派生类中的纯虚拟函数,但它不起作用。我只想重写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 : ProduceItem
。class
es的默认继承级别为private
。
更改为class Celery : public ProduceItem
请注意,当您删除该指针时,您将泄漏内存,因为您没有虚拟析构函数。只需在类中添加这样的定义:
virtual ~GroceryItem() {}
默认情况下,类的继承是私有的。通常,在您的情况下,您想要公共继承。因此:
class Celery : public ProduceItem
在CCD_ 5上也是类似的。
注意,对于structs,默认情况下继承是公共的(如果需要,可以说struct Foo : private Bar
)。
相关文章:
- std::具有相同基类的类的变体
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 基类中的函数名称解析
- C++初始化基类
- 如何通过派生类函数更改基类中的向量
- 如何定义一个纯抽象基类
- 如何使用基类指针引用派生类成员
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- 如何在派生类中不显式调用base::func()的情况下从基类执行虚拟函数
- 通过"a pointer of the base class"访问未在基类中声明的子类的方法或属性(动态)
- 我如何调用基类的虚拟函数定义,这些定义在Ampract Base类和C 中的派生类中都有定义
- 无法将"derived"强制转换为其私有基类"base"
- 运算符 const Base&() 是否应该用于无法访问的基类?
- 子构造函数无法识别基类的成员:平均值,西格玛"is not a nonstatic data member or base class"
- 如何在创建新的 obj() 时调用基类构造函数 new base(argT argV)