c++ - 使用带有模板基类的类作为基类参数

标签 c++ class inheritance vector arguments

我是不是漏掉了什么?或者是否有不允许这样做的原因?

// 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 中得到一些不是 MapImage 的对象。但是,由于 DrawItems 有一个 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/

上一篇:c++ - 内存编辑功能

下一篇:C++动态数组

相关文章:

c++ - 具有智能数组对象的类

python - 如何在一个主循环中创建两个 Tk 实例?

python - 有没有办法在 Python 中调用定义子类的方法?

java - java中不同的子类对父类的方法是否有可能有不同的可见性

c++ - dynamic_cast 与 base 中的虚拟 AsDerived 方法

c++ - C++ 中的 GStreamer 管道

c++ - float1 与 CUDA 中的 float

c++ - 使用 OpenCV c++ 进行对比度拉伸(stretch)的 RGB 彩色图像直方图

c++ - 使用多路复用搜索 C/C++ 网络库

python - 用 Python 编写向量(数学)类