【发布时间】: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