gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:02 27 4
gpt4 key购买 nike

我正在尝试使用指针迭代 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com