Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用具有模板基类的类作为基类参数_C++_Class_Inheritance_Vector_Arguments - Fatal编程技术网

C++ 使用具有模板基类的类作为基类参数

C++ 使用具有模板基类的类作为基类参数,c++,class,inheritance,vector,arguments,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>

我是不是遗漏了什么?或者这是不允许的原因

// 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);
//类声明
MapImage类:公共MapEntity,公共Vector2D{};
//变量声明
病媒健康包;
//功能
作废图纸项目(SDL_表面*目的地,标准::矢量和项目,SDL_表面*图像);
//实施
DrawItems(目标、healthpack、healthpack_图像);

由于HealthPack是MapImage类的std::vector,而MapImage具有基类Vector2D,“std::vector HealthPack”是否应该与“std::vector&items”兼容,因为它们具有相同的基类?

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

考虑DrawItems是否将Vector2D对象(一个不是MapImage的对象)插入到items中:在矢量中会有一些不是MapImage的对象。然而,因为DrawItems有一个向量,所以从它的角度来看,插入是完全有效的

而是在迭代器上传递迭代器范围和模板:

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);
  }
}

看起来您还需要添加const,但我保留了与您相同的代码。

否。基类的向量本身并不是派生类向量的基类

考虑DrawItems是否将Vector2D对象(一个不是MapImage的对象)插入到items中:在矢量中会有一些不是MapImage的对象。然而,因为DrawItems有一个向量,所以从它的角度来看,插入是完全有效的

而是在迭代器上传递迭代器范围和模板:

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);
  }
}
您似乎还需要添加常量,但我保留了与您相同的代码。

不需要

确实可以从MapImage向上转换为Vector2D,但该向量是不相关的类型。 您是希望创建直接案例还是副本?后者不会发生,因为对向量的引用是非常量的

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

确实可以从MapImage向上转换为Vector2D,但该向量是不相关的类型。 您是希望创建直接案例还是副本?后者不会发生,因为对向量的引用是非常量的


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

是。你得到了什么编译错误?使用或反勾号,这样你的向量就不会在问题文本中被错放(隐藏)。是的。你得到了什么编译错误?使用或反勾号,这样你的向量就不会在问题文本中被错放(隐藏)。
// this: DrawItems(dest, healthpacks, healthpack_image);
// becomes:
for (auto &x : healthpack) DrawItem(dest, x, healthpack_image);