下面是我的角色类及其子类的 .cpp 版本。我正在尝试让 attack() 函数正常工作。我做了一些更改,当前的错误处理了 adjustHP() 函数中的“在非成员函数中无效使用 'this'”。在我的主要课程中,我正在实例化一个玩家扮演的战士对象,而地精则是一个无法控制的敌人。
字符.cpp
character::character(double hp ,double atk, double defense, double speed){
this->hp= hp;
this->atk = atk;
this->defense = defense;
this->speed = speed;
}
double character::getHP() {
return this->hp;
}
double character::getATK() {
return this->atk;
}
double character::getDEFENSE() {
return this->defense;
}
double character::getSPEED() {
return this->speed;
}
战士.cpp
Warrior::Warrior():character(hp,atk,defense,speed) { // Constructor
this->hp= 50;
this->atk = 50;
this->defense = 50;
this->speed = 50;
}
void Warrior::adjustHP(double adjustBy) {
this->hp = this->hp - adjustBy;
}
void Warrior::attack(character* enemy) {
enemy->adjustHP(10);
}
妖精.cpp
Goblin::Goblin() : character(hp,atk,defense,speed) { // Constructor
this->hp= 60;
this->atk = 40;
this->defense = 40;
this->speed = 40;
}
void adjustHP(double adjustBy) {
this->hp = this->hp-adjustBy;
}
void Goblin::attack(character* playerChoice ) {
playerChoice->adjustHP(10);
}