簡體   English   中英

C++ “在非成員函數中無效使用‘this’”,

[英]C++ “Invalid use of 'this' in non-member function”,

下面是我的角色 class 及其子類的 .cpp 版本。 我試圖讓攻擊() function 工作。 我做了一些更改,當前錯誤處理了adjustHP() function 中的“在非成員函數中無效使用'this'”。 在我的主要 class 中,我正在實例化玩家扮演的戰士 object,而地精則是無法控制的敵人。

字符.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);
}

比較你的

void adjustHP(double adjustBy) {

與您的意圖:

void Goblin::adjustHP(double adjustBy) {

C++ 不會阻止您在 goblin.cpp 中定義不相關的免費adjustHP goblin.cpp並在該文件中保留Goblin::adjustHP未定義。

在 goblin.cpp 中,您將 adjustHP 定義為非成員 function。 它應該是:

void Goblin::adjustHP(double adjustBy) {
this->hp = this->hp-adjustBy;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM