二进制 '==':未找到采用 'Enemy' 类型左侧操作数的运算符(或者没有可接受的转换)

binary '==': no operator found which takes a left-hand operand of type 'Enemy' (or there is no acceptable conversion)

本文关键字:或者 运算符 转换 操作数 可接受 类型 二进制 Enemy      更新时间:2023-10-16

我正在做一个游戏,我试图用布尔值找到敌人应==true。 我有一个敌人标准::列表,我个人不知道代码有什么问题。 如果敌人有 shouldDie == 真,我只会播放动画。 希望你能帮助我理解为什么我得到错误。

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

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

相关文章: