2011-01-21 35 views
1

ここに何か不足していますか?またはこれが許可されていない理由はありますか? healthpacksのでテンプレートの基本クラスを基本クラスの引数として使用するクラス

// 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クラスのベクターSTDであり、そしてMapImageは、ベースクラスVector2Dを有し、「STD ::ベクトルhea​​lthpacks」は彼らので、「STD ::ベクター&アイテム」と互換性があってはなりません同じ基本クラスですか?

+0

はい。どのようなコンパイルエラーがありますか? –

+0

<またはbackticksを使用して、のベクトルが質問テキストに誤って解析されることはありません()。 –

答えて

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

をまたはコンテナ上:

代わり

、イテレータイテレータ範囲とテンプレートを渡す代わりに、すべてのDrawItemsのが、それでもDrawItemと

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

それとも、私は上記の宣言としておそらく新しいループのfor-eachループを使用してください:

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

また、 const。しかし、私はあなたのようにコードを残しました。

+0

良い点*ほこり*ありがとうございます。 – bitwise

1

確かに、MapImageからVector2Dにアップキャストできますが、ベクトル<>は無関係のタイプです。 ダイレクトケースやコピーを作成する予定ですか?後者はベクトル<>への非const参照のために起こりません。

なぜですか?これらは単なる配列であり、イテレータはレコードのサイズを知る必要があります。これは異なるタイプのもので異なるでしょう。

関連する問題