c++ - 二进制 '==':找不到使用 'Enemy'类型的左操作数的运算符(或者没有可接受的转换)

标签 c++ stl

我正在制作游戏,并且尝试通过bool shouldDie == true找到敌人。
我有一个敌人std::list,我个人不知道代码出了什么问题。
如果敌人的shouldDie == true,那么我将播放动画。
希望您能帮助我理解我为什么得到此错误。

我也没有重载==运算符,我已经在线搜索了,不确定是否有必要...

bool foundEnemy(Enemy& enemy)
{
    return enemy.shouldDie == true;
}
void Enemy::PlayDeathAnimation(std::list<Enemy>& enemies)
{
    dead = true;

    auto it = std::find_if(enemies.begin(), enemies.end(), foundEnemy); // where I think the error is
    auto enemy = std::next(it, 0);

    if (animationClock.getElapsedTime().asSeconds() >= 0.05f)
    {
        enemy->icon.setTextureRect(animationFrames[animationCounter]);
        if (animationCounter >= 8)
        {
            enemies.remove(*enemy);
        }
        animationCounter++;
        animationClock.restart();

    }
}
class Enemy : public Entity
{
public:
    Enemy() {}
    Enemy(sf::Vector2f position, sf::Texture* texture,Player* target);
    ~Enemy();

    void Update(sf::RenderWindow* window, float tElapsedTime);
    void Draw(sf::RenderWindow* window);
    void Fire(float tElapsedTime);
    void CheckBullets();
    void CheckEnemyBullets();
    void CheckHealth();

    void SetPosition(float x, float y);

    bool shouldDie = false;

    void PlayDeathAnimation(std::list<Enemy>& enemies);



private:

    bool dead = false;

    sf::Texture* deathSpriteSheet;
    std::vector<sf::IntRect> animationFrames;

    std::vector<Bullet> bullets;
    sf::RectangleShape origin;
    sf::RectangleShape aim;
    Player* target;

    int animationCounter = 0;
    sf::Clock animationClock;

};

最佳答案

该错误实际上不在您认为的位置,而是以下几行。

if (animationCounter >= 8)
{
    enemies.remove(*enemy); // here
}

您正在使用std::list::remove函数,该函数将搜索列表中与给定元素匹配的任何元素并将其删除。要知道哪个元素与给定的相同,它需要知道如何比较它们,因此需要operator ==
请改用 std::list::erase() -此函数接受迭代器,并将删除您指向的确切元素。
if (animationCounter >= 8)
{
    enemies.erase(enemy); // no dereference of the iterator
}

旁注-编译器是非常有用的工具。如果它检测到错误,它将使您指向发生错误的直线和列,尽管有时此信息可以很好地隐藏在大量其他(不太有用)的打印物中。

如果您还不了解编译器的语言,则可以将整个错误消息复制并粘贴到您的SO问题中,这将有助于我们更快地诊断错误。

关于c++ - 二进制 '==':找不到使用 'Enemy'类型的左操作数的运算符(或者没有可接受的转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59471902/

相关文章:

c++ - 对命名空间范围感到困惑!

Java JNI JAWT 错误未解析的外部符号 __imp__JAWT_GetAWT@8

c++ - std::map find_if 条件样式混淆

c++ - std::vector 是否使用 push_back 复制对象?

c++ - 使用ADS 1.2编译器和ARM11 RVCT2.2为ARM9编码时映射错误

c++ - STL 矢量化 map - 寻找最佳实践

c++ - STL容器泄漏

c++ - 握手失败 : certificate verify failed (Boost ASIO)

c++ - 作为右值 (c++) 在函数中传递的左值会发生什么?

c++ - 从 C++ 中的指针访问数组元素