在检查一下有没有错误
时间: 2024-02-20 13:02:05 浏览: 10
好的,我再检查一下代码,看看是否有错误:
```c++
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
// 生物基类
class Creature {
public:
Creature(int hp, int attack) : m_hp(hp), m_attack(attack) {}
virtual ~Creature() {}
virtual void attack(Creature& other) {
cout << "Creature attacks " << typeid(other).name() << endl;
other.defend(m_attack);
}
virtual void defend(int attack) {
int damage = attack - m_defense;
if (damage < 0) damage = 0;
m_hp -= damage;
cout << "Creature takes " << damage << " damage" << endl;
if (m_hp <= 0) {
cout << "Creature is dead" << endl;
m_hp = 0;
}
}
protected:
int m_hp;
int m_attack;
int m_defense;
};
// 龙类
class Dragon : public Creature {
public:
Dragon(int hp, int attack) : Creature(hp, attack) {
m_defense = 5;
m_name = "Dragon";
}
virtual void attack(Creature& other) {
cout << "Dragon breathes fire on " << typeid(other).name() << endl;
other.defend(m_attack);
}
private:
string m_name;
};
// 狼类
class Wolf : public Creature {
public:
Wolf(int hp, int attack) : Creature(hp, attack) {
m_defense = 3;
m_name = "Wolf";
}
virtual void attack(Creature& other) {
cout << "Wolf bites " << typeid(other).name() << endl;
other.defend(m_attack);
}
private:
string m_name;
};
int main() {
srand(time(nullptr));
Dragon dragon(50, 10);
Wolf wolf(30, 8);
while (dragon.m_hp > 0 && wolf.m_hp > 0) {
int r = rand() % 2;
if (r == 0) {
dragon.attack(wolf);
} else {
wolf.attack(dragon);
}
cout << "Dragon HP: " << dragon.m_hp << endl;
cout << "Wolf HP: " << wolf.m_hp << endl;
cout << endl;
}
return 0;
}
```
经过检查,我没有发现代码中的语法错误。如果你还有其他问题,可以继续问我。