3,用多态方法完成课程示例英雄无敌,定义至少5个怪物,用c++写出相关代码
时间: 2023-03-25 18:02:41 浏览: 155
C++ 多态的几种方法和代码示例
我可以回答这个问题。以下是用多态方法完成课程示例英雄无敌的相关代码:
#include <iostream>
using namespace std;
class Monster {
public:
virtual void attack() = ;
};
class Dragon : public Monster {
public:
void attack() {
cout << "Dragon attacks with fire breath!" << endl;
}
};
class Goblin : public Monster {
public:
void attack() {
cout << "Goblin attacks with a rusty sword!" << endl;
}
};
class Troll : public Monster {
public:
void attack() {
cout << "Troll attacks with a giant club!" << endl;
}
};
class Skeleton : public Monster {
public:
void attack() {
cout << "Skeleton attacks with a bow and arrow!" << endl;
}
};
class Zombie : public Monster {
public:
void attack() {
cout << "Zombie attacks with a bite!" << endl;
}
};
int main() {
Monster* monsters[5];
monsters[] = new Dragon();
monsters[1] = new Goblin();
monsters[2] = new Troll();
monsters[3] = new Skeleton();
monsters[4] = new Zombie();
for (int i = ; i < 5; i++) {
monsters[i]->attack();
}
return ;
}
阅读全文