2016-03-01 188 views
-1

我得到一個編譯錯誤「無法將'芯片'轉換爲'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); 
} 
+0

可以顯示GroceryCart AddItemToCart方法嗎? – MtRoad

+0

在最下面 – Bobby

+2

您應該在問題中標記語言。 – mattsap

回答

0

提供完整的錯誤日誌,檢查該容器與指針參數來GroceryItem(< GroceryItem *>)

正如有人指出的

delete[] itemName; //destructor 

但是你也必須定義非平凡的copy-constructor/operator =,因此最好用std :: string替換char *,也需要定義基本抽象類的析構函數,即使它是純虛擬的。