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

标签 c++ c++11 vector polymorphism

我正在尝试使用指针迭代 vector 我有一个 vector 叫做:

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

如您所见,我正在尝试以一种仍然允许我调用函数并将多态类解析为其他多态类的方式进行迭代(因此它在被解析为 vector 之前声明的原因),我保留的内容得到是错误的:

C2839: invalid return type 'GameObject *const *' for overloaded 'operator ->'

和错误:

C2039: 'update' : is not a member of 'std::_Vector_const_iterator<_Ty,_Alloc>'

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

最佳答案

在 C++11 中:

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

关于C++ 使用 std::vector 迭代类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23761396/

相关文章:

c++ - 多维数组作为类成员分配在堆上

c++ - 将 vector 转换为数组

c++ - 为 i686-elf 交叉编译和链接 libstdc++(在 Ubuntu 16.04 上使用 g++)

c++ - noexcept,堆栈展开和性能

c++ - 我的代码在 Dev c++ IDE 中运行良好,但在 Linux 终端中则不然。 (特别是在 'while' 循环部分。)

c++ - VS2013 编译器 : 'CObject::CObject' : cannot access private member declared in class 'CObject'

python - 如何在 Numpy(或其他 Python 解决方案)中利用外积的对称性?

C++ - 已排序 std::vector 中元素的索引

c++ - 如何在 iOS 中添加带有 PCM 数据/缓冲区的可播放(例如 wav、wmv) header ?

c++ - 当作为参数传递的对象超出范围时,析构函数是否会调用自身?