2011-01-21 55 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,但是矢量<>是不相关的类型。 您是否期待直接创建案例或创建副本?后者将不会发生,因为对矢量<>的非常量引用。

为什么?支持这些仅仅是数组,迭代器需要知道记录的大小,这对于不同的类型会有所不同。

相关问题