2011-01-21 58 views
1

我在這裏丟失了什麼嗎?或者有沒有原因,這是不允許的?使用模板基類作爲基類參數的類

// the class declaration 
class MapImage : public MapEntity, public Vector2D {}; 

// the variable declaration 
std::vector<MapImage> healthpacks; 

// the function 
void DrawItems(SDL_Surface *dest, std::vector<Vector2D> &items, SDL_Surface *image); 

// the implementation 
DrawItems(dest, healthpacks, healthpack_image); 

因爲healthpacks是MapImage類的一個std ::向量,MapImage有基類的Vector2D,不應該「的std ::矢量healthpacks」與兼容「的std ::矢量&項目」,因爲它們有相同的基類?

+0

是的。你會得到什麼編譯錯誤? – 2011-01-21 05:07:41

+0

使用<或反引號,這樣您的向量不會在問題文本中被誤解(與變得隱藏)。 – 2011-01-21 05:34:51

回答

5

否。基類向量本身並不是派生類向量的基類。

考慮如果DrawItems插入的Vector2D對象,一個是一個MapImage,成件物品:你會的東西是不是在矢量< MapImage一個MapImage>。但是,由於DrawItems具有矢量< Vector2D>,所以從插入角度來看,插入將是完全有效的。

相反,通過對迭代的迭代器範圍,模板:

void DrawItem(SDL_Surface *dest, Vector2D &item, SDL_Surface *image); 

template<class Iter> 
void DrawItems(SDL_Surface *dest, Iter begin, Iter end, SDL_Surface *image) { 
    for (; begin != end; ++begin) { 
    DrawItem(dest, *begin, image); 
    } 
} 

或容器上:

template<class Container> 
void DrawItems(SDL_Surface *dest, Container &items, SDL_Surface *image) { 
    typename Container::iterator begin = items.begin(), end = items.end(); 
    for (; begin != end; ++begin) { 
    DrawItem(dest, *begin, image); 
    } 
} 

或者,而不是在所有DrawItems但仍與DRAWITEM正如我上面聲明,也許使用新的每個循環:

// this: DrawItems(dest, healthpacks, healthpack_image); 
// becomes: 
for (auto &x : healthpack) DrawItem(dest, x, healthpack_image); 

它也出現你需要添加常量,但我已經離開了你的代碼。

1

那麼,沒有。

當然你可以從MapImage上傳到Vector2D,但是矢量<>是不相關的類型。 您是否期待直接創建案例或創建副本?後者將不會發生,因爲對矢量<>的非常量引用。

爲什麼?支持這些僅僅是數組,迭代器需要知道記錄的大小,這對於不同的類型會有所不同。

相關問題