c ++如何跨多个类更改同一个对象?

ann*_*nna 3 c++ pointers class object

诺比在这里.我正在尝试跨多个类对Player对象进行更改mainCharacter.我目前有一个Player声明如下所示的对象.在Player能够瞬移到各种世界和怪物进行战斗.

所有这些代码都有效.一旦一个世界的敌人被击败,他们就会被击败.我的问题是当他传送到另一个世界时,他们Player的统计数据都被重置为默认值; 即使在前世界遭受敌人的伤害之后,他仍然拥有完整的生命值.

如何Player跨多个类或世界对同一对象进行更改?我认为我的声明中存在问题,但我不确定.我很感激任何意见.谢谢!

mainCharacter对象被声明:

class SpaceList
{
    protected:
        class SpaceNode
        {
            friend class SpaceList;
            Player mainCharacter;
            Space* thisSpace;
            SpaceNode* next;
            SpaceNode(int m, SpaceNode* next1 = NULL)
            {
                if(m == 0)
                {
                    thisSpace = new EntranceHall(&mainCharacter);
                }
                else if(m == 1)
                {
                    thisSpace = new WaterSpace(&mainCharacter);
                }
Run Code Online (Sandbox Code Playgroud)

部分Player.hpp:

class Player: public Interactable
{
    protected:
        Backpack myBackpack;
    public:
        Player();
        virtual interactableType getInteractableType();
        virtual int interact();
        virtual int attack();
        virtual void defend(int);
Run Code Online (Sandbox Code Playgroud)

部分Player.cpp:

Player::Player()
{
    healthPoints = 10;
    numberOfAttackDice = 1;
    sidesOfAttackDice = 6;
    numberOfDefendDice = 1;
    sidesOfDefendDice = 6;
}
Run Code Online (Sandbox Code Playgroud)

mainCharacterEntrance(Entrance.cpp)开始:

EntranceHall::EntranceHall(Interactable* mainCharacter)
{
    interactableGrid[6][3] = mainCharacter;
    interactableGrid[0][3] = new Portal(0);//entrance portal
    interactableGrid[3][3] = new InterestPoint(0);//stone mural
}
Run Code Online (Sandbox Code Playgroud)

mainCharacter可能以后传送到Water World,默认值reset(Waterspace.cpp):

WaterSpace::WaterSpace(Interactable* mainCharacter)
{
    interactableGrid[3][0] = mainCharacter;
    interactableGrid[3][3] = new Boss(this->getSpaceType());
Run Code Online (Sandbox Code Playgroud)

Log*_*uff 6

卸下有-A之间的关系SpaceNode以及Player-创建的实例Player之外的地方,并用一个指针引用它,就像你已经习惯了.或者只是制作它static,以便只有一个实例不会被重建(或者为每个实例单独构建SpaceNode).


笔记:

  • 不要自己实现链表,这个数据结构甚至不适合这里.试试std::vector.

  • 更好地切换到智能指针.你甚至可能在不知情的情况下泄漏记忆.