C++ 向量迭代错误

C++ Vector Iteration Error

monster* monster1 = new monster("Frankenstein", "The Ugly One", BackYard);
Player* player1 = new Player("Corey", "The Chosen one", Atrium);
Player* player2 = new Player("Darth Vader", "The Evil One", Atrium);
vector<Agent*> agents;
agents.push_back(monster1);
agents.push_back(player1);
agents.push_back(player2);

while (true)
{
    vector<Agent*>::iterator it;

    for (it = agents.begin(); it < agents.end(); it++) {
        it->act();                                            // Error here
        if (it->act() == false)                               // Error here
            return 0;
    }

    ...
}

我收到一条错误消息:

Member reference base type 'Agent *' is not a structure or union.

我真的不明白为什么导航矢量不起作用。

it 指向 Agent* 而不是 Agentit-> 将尝试在指针而非对象上调用函数。您需要做的是取消引用迭代器,然后调用成员函数。

(*it)->act();   
vector<Agent*> agents;

是指针向量,如果它是对象向量,则必须单独执行 it->act(); 。但在这种情况下,您首先需要取消引用 it ,然后再取消引用您通过这样做获得的指针。指针和迭代器各自引入一层间接寻址,这使它成为两层:

(*it)->act();
(**it).act(); // equivalent

因为vector的元素类型是Agent *,不是Agent。迭代器箭头运算符 returns 对向量中元素的引用 - 但它没有 act 函数(因为它是指向 Agent 而不是 Agent 的指针).您的选择是:

    (*it)->act();

或者重写整个循环:

    for (auto pAgents : agents)
    {
        pAgents->act();
    }

当你在谈论它时,我强烈建议将其设为 unique_ptr 的向量。这样您就不必担心内存处理问题。

vector<std::unique_ptr<Agent>> agents;
agents.push_back( std::make_unique<Monster>("Frankenstein", "The Ugly One", BackYard));
agents.push_back( std::make_unique<Player>("Corey", "The Chosen one", Atrium) );
agents.push_back( std::make_unique<Player>("Darth Vader", "The Evil One", Atrium) );

while (true)
{

    for (auto pAgent : agents){
        pAgent->act();
        if (!pAgent->act())
            return 0;
    }
}