C ++使用std :: vector迭代类指针

时间:2014-05-20 13:37:20

标签: c++ c++11 vector polymorphism

我试图使用指针迭代向量 我有一个名为:

的向量
 std::vector<GameObject*> objects;

以及一系列类似的功能:

void Game::update()
 {
    std::vector<GameObject*>::iterator itr;
    for( itr = objects.begin();itr < objects.end();++itr)
    {
        itr->update();//I need to call a abstract function in the GameObject Class
    }
 }
 Game::~Game()
 {

    delete ball;
    delete player;
 }
Game::Game()
{
    ball = new GOBall(800/2 - GOBall::SIZE/2,600/2 - GOBall::SIZE/2);
    player = new GOPlayer(0, 600/2 - GOPlayer::SIZEY/2,ball);
    objects.push_back(ball);
    objects.push_back(player);
}

正如你所看到的那样,我试图以一种方式迭代,这种方式仍然允许我调用函数并将多态类解析为其他多态类(因此它在被解析为向量之前声明它的原因),我保留的得到是错误:

  

C2839:无效的返回类型'GameObject * const *'用于重载'运算符 - &gt;'

和错误:

  

C2039:'update':不是'std :: _ Vector_const_iterator&lt; _Ty,_Alloc&gt;'

的成员

告诉我我不能通过迭代器调用ball->update()player->update(),所以我该怎么做?

4 个答案:

答案 0 :(得分:9)

在C ++ 11中:

for (GameObject* gameObject : objects) {
    gameObject->update();
}

答案 1 :(得分:7)

您需要取消引用迭代器

(*itr)->update();

这是一个简短的说法:

GameObject* pGameObject = *itr;
pGameObject->update();

答案 2 :(得分:4)

我们可以更好地使用基于范围的for循环:

for (auto& game_object : objects)
  game_object->update();

答案 3 :(得分:0)

更复杂的方法是创建自己的自定义迭代器适配器。这是一个例子(完整的例子将编译并运行):

#include <iostream>

#include <vector>
#include <memory>

struct GameObject {
    GameObject(int id)
    : _id { id }
    {}

    virtual void fireLazorz() {
        std::cout << "Game Object " << _id
        << ": I'm a-firin' mah lazorz!" << std::endl;
    }
private:
    int _id;
};


using vec_t = std::vector<std::unique_ptr<GameObject>>;

struct gameobject_deref_iterator : public vec_t::const_iterator
{
    using parent_t = vec_t::const_iterator;

    gameobject_deref_iterator(parent_t src)
    : parent_t(std::move(src))
    {

    }

    // override the indirection operator
    GameObject& operator*() const {
        return *(parent_t::operator*());
    }

    GameObject* operator->() const {
        return parent_t::operator->()->get();
    }

};
using namespace std;

int main()
{
    vec_t gameObjects;

    for(int i = 0 ; i < 10 ; ++i) {
        gameObjects.emplace_back(
                                 new GameObject{ i }
                                 );
    }

    // now iterate the game objects, starting with the 5th one

    gameobject_deref_iterator first { next(begin(gameObjects), 5) };
    gameobject_deref_iterator last { end(gameObjects) };
    cout << "We have " << last - first << " GameObjects:" << endl;
    for(auto it = first ; it != last ; ++it) {
        it->fireLazorz();
    }

    return 0;
}

输出:

Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1

Executing the program....
$demo 
We have 5 GameObjects:
Game Object 5: I'm a firin my lazorz!
Game Object 6: I'm a firin my lazorz!
Game Object 7: I'm a firin my lazorz!
Game Object 8: I'm a firin my lazorz!
Game Object 9: I'm a firin my lazorz!