0

以下は、私の文字クラスとそのサブクラスの .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);
}

goblin.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);
}
4

2 に答える 2

1

あなたの比較

void adjustHP(double adjustBy) {

あなたが意図したもので:

void Goblin::adjustHP(double adjustBy) {

C++ では、関連のないフリーadjustHP関数を で定義して、そのファイルで未定義のままにgoblin.cppすることはできません。Goblin::adjustHP

于 2020-06-09T07:06:45.893 に答える
1

goblin.cpp では、adjustHP を非メンバー関数として定義しました。次のようになっているはずです。

void Goblin::adjustHP(double adjustBy) {
this->hp = this->hp-adjustBy;
}
于 2020-06-09T07:08:37.240 に答える