C++ 虚函数不重写

问题描述 投票:0回答:1
#include <iostream>
using namespace std;

class character {
private:
public:
  character(string n, int h, int a){
  }
  virtual int getHealth() = 0;
  virtual int getAttack() = 0;
  virtual string getName() = 0;
  virtual void updateHealth() = 0;
  virtual void updateAttack(int a) = 0;
  virtual void attackCharacter(character &b) = 0;
  virtual void print() = 0;
};
class entity : public character {
private:
string name;
int health;
int attack;
public:
  entity(string n, int h, int a) : character(n, h, a) {
    n = name; h = health; a = attack;
  }
  void updateAttack(int a) override { attack = a; }
  void attackCharacter(character &b) override { b.updateHealth(); b.getHealth(); }
  int getHealth() override { return health; }
  string getName() override { return name; }
  virtual void print() override {cout<<name<<" "<<health<<endl;}
  int getAttack() override { return attack; }
 void updateHealth() override { health = health - attack; }
};

#include <iostream>
#include "character.h"
using namespace std;

int main() {
   character* player = new entity("Player", 50, 5);
   entity* enemy = new entity("Enemy", 50, 5);
   player->print();
   enemy->print();
  }

输出为 0,而不是被纯虚拟语句覆盖。是否有我遗漏的东西导致它无法被覆盖?我正在使用类字符来定义变量并尝试在子类实体中重新定义它们

c++ virtual-functions
1个回答
1
投票

问题出在实体构造函数中。您将 n、h 和 a 的值分别分配给成员变量 name、health 和attack,而不是初始化它们。

你的构造函数应该是这样的:

entity(string n, int h, int a)
  : character(n, h, a), name(n), health(h), attack(a) {}
© www.soinside.com 2019 - 2024. All rights reserved.