【问题标题】:binary '==': no operator found which takes a left-hand operand of type 'Enemy' (or there is no acceptable conversion)二进制“==”:未找到采用“Enemy”类型的左操作数的运算符(或没有可接受的转换)
【发布时间】:2019-12-24 17:36:15
【问题描述】:

我正在制作一个游戏,我正在尝试使用 bool shouldDie == true 来寻找敌人。 我有一个 Enemy 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;

};

【问题讨论】:

  • 什么是shouldDie?你能告诉我们Enemy 标头吗?
  • 它是 Enemy 类的公共 bool 成员
  • 那么要么你向我们展示了错误的代码片段,要么你的编译器出错了,因为它抱怨==Enemy 作为左侧操作数。 (还有专业提示,return enemy.shouldDie == true; 可以是 return enemy.shouldDie;。您永远不必与布尔文字进行比较)
  • 我再查一下
  • 如果没有找到,它会返回enemy.end(),在这种情况下你的代码会有问题。

标签: c++ stl


【解决方案1】:

错误其实不是你想的,而是下面几行。

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 问题中,这将有助于我们更快地诊断错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 2012-07-23
    相关资源
    最近更新 更多