2010-09-25 20 views
0

實現純虛I類具有以下類:問題在C++

#include <string> 
#include <stack> 
#include <queue> 
#include "map.h" 

using namespace std; 

#ifndef CONTAINER_H_ 
#define CONTAINER_H_ 

struct PathContainer { 
    int x, y; 
    string path; 
}; 

class Container { 
public: 
    virtual void AddTile(string, FloorTile *) = 0; 
    virtual void ClearContainer() = 0; 
    virtual PathContainer *NextTile() = 0; 
}; 

class StackImpl : public Container { 
private: 
    stack<PathContainer> cntr; 
public: 
    StackImpl(); 
    void AddTile(string, NeighborTile *); 
    void ClearContainer(); 
    PathContainer *NextTile(); 
}; 

class QueueImpl : public Container { 
private: 
    queue<PathContainer> cntr; 
public: 
    QueueImpl(); 
    void AddTile(string, NeighborTile *); 
    void ClearContainer(); 
    PathContainer *NextTile(); 
}; 
#endif 

當我嘗試創建StackImpl或QueueImpl對象像這樣:

Container *cntr; 
cntr = new StackImpl(); 

Container *cntr; 
cntr = new QueueImpl(); 

我在編譯時得到以下錯誤:

escape.cpp: In function ‘int main(int, char**)’: escape.cpp:26: error: cannot allocate an object of abstract type ‘StackImpl’ container.h:23: note: because the following virtual functions are pure within ‘StackImpl’: container.h:18: note: virtual void Container::AddTile(std::string, FloorTile*)

任何想法?

+1

還要注意,你的基類應該幾乎肯定有一個虛擬析構函數(不要把它變成純虛擬的,只是虛擬的)。 – 2010-09-25 23:42:46

+2

永遠不要在頭文件中放置'using namespace std;' - 或任何'using namespace'聲明。您將在每個包含您的標題的源文件中強加該聲明,因此這被認爲是一種非常糟糕的做法。 – Praetorian 2010-09-25 23:42:48

+0

@Praetorian:原則上我同意(所以我+1你,好先生),但至少'std'就是'std'。在全球使用的所有命名空間中,它可能是最少的罪惡。 :) – 2010-09-25 23:47:10

回答

5

typeid(NeighborTile *) != typeid(FloorTile *)。簽名不同,因此即使NeighborTile繼承自FloorTile,它們也不會被視爲「相同」方法。