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

Da_*_*oom 4 c++ polymorphism vector c++11

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

 std::vector<GameObject*> objects;
Run Code Online (Sandbox Code Playgroud)

和这些函数的负载:

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);
}
Run Code Online (Sandbox Code Playgroud)

正如你可以看到我想要的方式,仍然让我调用的函数,也解析polymorphistic类为其他polymorphistic类迭代(因此原因,其被解析到载体之前声明),我不断收到的错误:

C2839:重载'运算符 - >'的返回类型'GameObject*const*'无效

和错误:

C2039:'update':不是'std :: _ Vector_const_iterator <_Ty,_Alloc>'的成员

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

Jar*_*d42 9

在C++ 11中:

for (GameObject* gameObject : objects) {
    gameObject->update();
}
Run Code Online (Sandbox Code Playgroud)


Cor*_*mer 7

您需要取消引用迭代器

(*itr)->update();
Run Code Online (Sandbox Code Playgroud)

这是简短的说法:

GameObject* pGameObject = *itr;
pGameObject->update();
Run Code Online (Sandbox Code Playgroud)