引发异常:读取访问冲突。此-> ** p2 **为0xCCCCCCCC。发生

时间:2019-06-21 17:02:46

标签: c++ exception

我正在写一个基于控制台回合的动作格斗游戏。这段代码编译没有错误。我尝试为Player实例化一个对象,为Enemy实例化一个对象,然后使用敌人* p2来获取其健康状况,等等。当我运行程序时,指针本身似乎引起了问题,导致了异常。

class Unit
{
public:
    //default constructor and destructor
    Unit();
    virtual ~Unit();
    //interfaces
    virtual int attack() = 0;
    virtual void cast() = 0;

    void takeDamage(int);
    bool isAlive();
    //getters here
    virtual inline const string getName() const { return m_Name; }
    virtual inline int getHealth() const { return m_Health; }
protected:
    string m_Name;
    int m_Health;
};

class Player : public Unit
{
public:

    Player(void);
    virtual ~Player();

    void AddExperience();
    int attack(Unit* target);
    int getDamage();
private:
    int level;
    int experience;
    int actionsLeft;
};

class Enemy : public Unit
{

public:
    Enemy();
    virtual ~Enemy();
    int getExperience() const;
    int attack(Player* player);
    void msgDeath();
    void initialiseEnemy(int damage, int health);
protected:
    int m_xp;
    int m_damage;

};

//Game.h
    class Game
    {
    public:
        void playGame();
        void playerActionMenu();
    protected:
        Player *p1;
        Enemy *p2;
    };


//Game.cpp
void Game::playerActionMenu()
{
    p2->initialiseEnemy(15, 60);
    cout << "\n Enemy has " << p2->getHealth() << " health.";
    int choice = 0;
    cout << "Choose your move:" << endl
        << "1) Attack" << endl
        << "2) Assume defensive position." << endl;
    cin >> choice;
    switch (choice)
    {
    case 1:
        p1->attack(p2);
    }
    cout << "\nEnemy now has "<<p2->getHealth();
}

单位类是基类,敌人和玩家从中派生。其背后的逻辑是,当玩家攻击时,它应该以敌方目标为目标,然后访问该目标的生命值并减少其数量。

请帮助我。是什么导致错误?另外,您认为我处理多态性的方式有问题吗?

0 个答案:

没有答案