无法使子类正常工作

cant get subclasses to work properly

本文关键字:工作 常工作 子类      更新时间:2023-10-16

我制作了一个简单的基于文本的格斗游戏,但我在让我的子类工作时遇到了很多麻烦。

在我得到的许多错误中,最持久的是"我们的行定义"矮人"与"矮人"的任何声明都不匹配"

#include <iostream>
using namespace std;
class Poke{
protected:
    string race;
    int health, damage, shield;
public:
    Poke();
    Poke(int health, int damage, int shield);
    virtual int attack(Poke*);
    virtual int defend(Poke*);
    virtual int getHealth();
};

这是不同种族的一个子级别,还有 2 个具有不同攻击/生命值/盾牌级别的子

级别
// Dwarf: High health, Low attack, High defense
class Dwarf: public Poke {
public:
    string race = "Dwarf";
    int attack(Poke*);
    int defend(Poke*);
    int getHealth();
};

.cpp V

//DWARF
Dwarf::Dwarf(int health, int damage, int shield) {
    this->health = 100;
    this->damage = 50;
    this->shield = 75;
};
//attack
int Poke:: attack(Poke*){
    if (shield > (damage + rand() % 75)){
        cout << "Direct Hit! you did" << (health - damage) << "points of damage";
    }
    else {std::cout << "MISS!"<<;
    }
    return 0;
};
int Poke:: attack(Poke*){
    Enemy this->damage ;
};

我正在为玩游戏的人使用一个玩家类,该游戏将使用"Poke"

class Player{
    int wins, defeats, currentHealth;
    string name;
    Poke race;
    bool subscribed;
public:
    Player(int wins, int defeats, int currentHealth);
    int addWins();
    int addDefeats();
    int getWins();
    int getDefeats();
    int getHealth();

};

.cpp V

//getHealth
int Player::getHealth(){
    return this->currentHealth;
};

和计算机对手的"敌人"类:

class Enemy{
    int eHealth;
    Poke eRace;
public:
    Enemy (int eHealth, Poke eRace);
    int getEHealth;
};

.cpp V

int Enemy:: getEHealth(){
    return this->eHealth;
};

任何帮助将不胜感激!!

构造

函数不是继承的。您必须声明一个与您的定义匹配的Dwarf构造函数。

我想你也会遇到麻烦:

string race = "Dwarf";

不能以这种方式初始化类成员。它必须在构造函数中初始化。

编辑:

你似乎不明白我所说的声明是什么意思。将Dwarf类声明更改为如下所示:

// Dwarf: High health, Low attack, High defense
class Dwarf: public Poke {
public:
    string race;
    Dwarf(int health, int damage, int shield); // <-- constructor declaration
    int attack(Poke*);
    int defend(Poke*);
    int getHealth();
};

编辑 2:

Dwarf构造函数还应调用Poke构造函数,如下所示:

Dwarf::Dwarf(int health, int damage, int shield) :
    Poke(health, damage, shield),
    race("Dwarf")
{
    // Nothing needed here.
};