我是不是漏掉了什么?或者是否有不允许这样做的原因?
// 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::vector,并且 MapImage 具有基类 Vector2D,因此“std::vector healthpacks”不应与“std::vector &items”兼容,因为它们具有相同的基类?
最佳答案
没有。基类 vector 本身不是派生类 vector 的基类。
考虑一下,如果 DrawItems 将一个 Vector2D 对象(一个不是 MapImage)插入到项目中:您将在 vector
相反,在迭代器上传递一个迭代器范围和模板:
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,也许使用新奇的 for-each 循环:
// this: DrawItems(dest, healthpacks, healthpack_image);
// becomes:
for (auto &x : healthpack) DrawItem(dest, x, healthpack_image);
看来您还需要添加常量,但我保留了您原来的代码。
关于c++ - 使用带有模板基类的类作为基类参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4755568/