【发布时间】:2012-10-25 19:55:55
【问题描述】:
我正在开发一款基于文本的有趣游戏,但我正在努力解决继承问题
来自基类。我有我的基类Being,它包含所有统计信息
我创造的任何角色。然后我有一个我想参加的课程Combat
来自Being 的所有统计数据(或者来自一个存在并将其传递到战斗中?)并执行
所有战斗的东西。但我不太了解继承,或者至少
如何在Main 中声明函数以使其工作。如果我继续攻击
Being 中的函数,我可以在 main 中写这行:
human.attack(monster);
但是将战斗拆分到另一个班级后,我不知道该怎么写 这主要是它的工作原理。请并感谢您的帮助!
class Being // Base Class
{
public:
string name, nameSpecialAttack; // Implement a special attack feature,
// that has a specific mutliplier #
// unique to each being
int attackBonus, attackMod; // was a float attackMod method for casting
// spells that double or halve a Being’s
// attack power.
int baseDamage; // base damage
int health, healthMax; // current health and max health
int mp, mpMax; // current mp and max mp
int arrows; // change to [ranged?] ammo
Being(); // Default Constructor
Being(string name, string nameSpecialAttack, int attackBonus,
int attackMod, int baseDamage, int health, int healthMax,
int mp, int mpMax, int arrows); // Constructor 2
// All my set and get functions
}
然后是我的派生类:
class Combat : public Being
{
private:
public:
void attack(Being& target);
};
战斗.cpp:
void Combat::attack(Being& target)
{
//unsigned seed = time(0);
//srand(seed);
// Rand # 0-99, * damage+1, /100, * attackMod, parse to int.
int damage = (int)(attackMod*( ( (rand()%100)*(baseDamage+1) /100) + attackBonus + (rand()%2)));
target.health -=damage;
cout << name << " attacks " << target.name << " doing " << damage << " damage!" << endl;
cout << target.name << "'s health: " << target.health << endl;
// Use getHealth() instead and put this function there
if(target.health <= 0)
{
cout << endl << name << " killed " << target.name << "! You have won the game! " << endl << endl;
cout << "Terminating AMnew World, Good Bye.\n" << endl << endl;
exit(0);
}
}
主要:
Being human("", "FirstofFurry", 2, 1, 2, 50, 50, 20, 30, 7); // A thing of
// class Being
Being monster("Armored Goblin", "Rawr", 2, 1, 2, 65, 59, 20, 20, 6);
int main()
{
human.attack(monster); // No longer works since attack is in
// combat class now
Sleep(3000);
cout << endl << endl;
monster.attack(human);
}
【问题讨论】:
-
这应该不是继承关系。你会说“战斗”是一种“存在”吗?我对此表示怀疑。
-
我觉得“战斗”是“可以进入战斗的东西”的缩写。
-
是的,我觉得Combat类在这里没用,方法可以在Being中
-
@FredLarson 我不知道为什么我忘记了这个基本原则。谢谢大家让我直截了当,当我不再那样想时,这让事情变得容易多了。
标签: c++ class inheritance derived-class