虚拟类和继承

时间:2016-03-01 01:41:52

标签: c++ inheritance virtual

我收到编译错误"无法转换' Chips'到#GroceryItem'而且我无法弄清楚如何将某些东西实际转换为虚拟类对象。老师提供了一个' GroceryCart'将GroceryItems添加到购物车中的主要类别'并打印出购物车。

class GroceryItem {
public:
    virtual ~GroceryItem();
    virtual float GetPrice() = 0;
    virtual char* GetDescription() = 0;
    virtual float GetWeight() = 0;
};



 #include "GroceryItem.h"

class Chips : public GroceryItem {
public:
    Chips();
    ~Chips();
    float GetPrice();
    char* GetDescription();
    float GetWeight();
private:
    float price;
    char* itemName;
    float weight;
};

#include "GroceryItem.h"
#include "Chips.h"

Chips::Chips() {
    price = 0.75;
    itemName = new char[5];
    itemName = "Chips";
    weight = 1.0;
}

Chips::~Chips() {
    delete this;
}

float Chips::GetPrice() {
    return price;
}

char* Chips::GetDescription() {
    return itemName;
}

float Chips::GetWeight() {
    return weight;
}



 int main(int argc, const char * argv[])
{
    GroceryCart c;
    c.AddItemToCart(new Chips);
    std::cout << c;
    return 0;
}
void GroceryCart::AddItemToCart(GroceryItem *i)
{
    items.push_back(i);
}

1 个答案:

答案 0 :(得分:0)

提供完整的错误日志,检查用指向GroceryItem(&lt; GroceryItem *&gt;)

的指针参数化的容器

有人指出

delete[] itemName; //destructor

但是你还必须定义非平凡的copy-constructor / operator =,所以最好用std :: string替换char *,也需要为基本抽象类定义析构函数,即使它是#s;纯虚拟。