C++ "Invalid use of 'this' in non-member function",
C++ "Invalid use of 'this' in non-member function",
以下是我的角色 class 及其子 class 的 .cpp 版本。我正在尝试让 attack() 函数发挥作用。我做了一些更改,当前错误处理 adjustHP() 函数中的 "invalid use of ‘this’ in non-member function"。在我的主要 class 中,我正在实例化玩家扮演的 Warrior 对象和 Goblin 作为无法控制的敌人。
character.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;
}
warrior.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);
}
比较你的
void adjustHP(double adjustBy) {
与您的预期一致:
void Goblin::adjustHP(double adjustBy) {
C++ 不会阻止您在 goblin.cpp
中定义不相关的自由 adjustHP
函数并在该文件中保留 Goblin::adjustHP
未定义。
在 goblin.cpp 中,您将 adjustHP 定义为非成员函数。
应该是:
void Goblin::adjustHP(double adjustBy) {
this->hp = this->hp-adjustBy;
}
以下是我的角色 class 及其子 class 的 .cpp 版本。我正在尝试让 attack() 函数发挥作用。我做了一些更改,当前错误处理 adjustHP() 函数中的 "invalid use of ‘this’ in non-member function"。在我的主要 class 中,我正在实例化玩家扮演的 Warrior 对象和 Goblin 作为无法控制的敌人。
character.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;
}
warrior.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);
}
比较你的
void adjustHP(double adjustBy) {
与您的预期一致:
void Goblin::adjustHP(double adjustBy) {
C++ 不会阻止您在 goblin.cpp
中定义不相关的自由 adjustHP
函数并在该文件中保留 Goblin::adjustHP
未定义。
在 goblin.cpp 中,您将 adjustHP 定义为非成员函数。 应该是:
void Goblin::adjustHP(double adjustBy) {
this->hp = this->hp-adjustBy;
}