【问题标题】:C++ "Invalid use of 'this' in non-member function",C ++“在非成员函数中无效使用'this'”,
【发布时间】:2020-09-28 07:00:40
【问题描述】:

以下是我的角色类及其子类的 .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);
}

【问题讨论】:

  • 请提供一个可重现的最小示例
  • 错误信息应该指向你准确的代码行,并使其非常明显。
  • 顺便说一句:目前,拥有 3 个类没有意义,你可以只使用 character Warrior()character Goblin() 做同样事情的免费函数
  • @Caleth 我正在尝试使用一些设计模式进行实践(特别是此处的策略),并将扩展该程序以区分战士和妖精。
  • 我认为严格来说你的Warrior::WarriorGoblin::Goblin 有未定义的行为,因为你在初始化它们之前使用了数据成员。 Warrior::Warrior() : character(50, 50, 50. 50) {}Goblin::Goblin() : character(60, 40, 40, 40) {} 是正确的

标签: c++ class pointers inheritance non-member-functions


【解决方案1】:

在 goblin.cpp 中,您将 adjustHP 定义为非成员函数。 应该是:

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

【讨论】:

    【解决方案2】:

    比较你的

    void adjustHP(double adjustBy) {
    

    如你所愿:

    void Goblin::adjustHP(double adjustBy) {
    

    C++ 不会阻止您在 goblin.cpp 中定义不相关的免费 adjustHP 函数并在该文件中保留 Goblin::adjustHP 未定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 2015-05-30
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多