Two objects that must reference each other. Bad idea?

I am developing a very small and simple game engine in C ++. I have a Creature class and a Weapon class. A Being must know what weapon (s) it has, and every Weapon must know a Being that has it. The main reason I would like the Weapon to know what this Creature is is to prevent it from destroying its own Creature (when the Weapon attacks, it detects all the Creatures it encounters and kills them, except for the Creature that has Weapon).

Here's what the (simplified) creature class looks like:

class Creature {
    private:
    Weapon* weapon_;
    public:
    void SetWeapon(Weapon* w){
        // do some other stuff (e.g. remove Weapon from any other Creatures)
        weapon_ = w;
        w->creature_ = this;
    }
}

Here's what the (simplified) weapon class looks like:

class Weapon{
    friend class Creature; // Creature needs access to creature_ pointer
    private:
    creature_;
}

As you can see, I made the Creature a Friend Weapon class so that the creature's setWeapon () method can set the pointer of the private creature_ appropriately.

:

  • , , , . , ? "", , , , ( ). , , ? Map/Entity, Inventory/Item .. , , "Container" "Item", . , , BOTH (.. , , ). , ?

  • ? , ?

  • , ?

. , , , .

+4
3

:

class Creature {
public:
    void SetWeapon(Weapon* w) {
        weapon_ = w;
        weapon_->SetCreature(this);
    }
private:
    Weapon* weapon_;
};

class Weapon {
public:
    void SetCreature(Creature* _creature) {
        m_owner = _creature;
    }
private:
    Creature* m_owner;
};

- , . , , , . , , , (, !).

+1
  • . , , goto . . .

  • , goto. BU .

: , , , . , , struct, , . , . ( struct). , .

0

Very often, objects turn back and forth. A common example is a pointer to a parent. Your concept is quite reasonable. Just make sure you have a destructor in place so that the object pointers are cleared.

In ~Weapon()remove the pointer Creaturewith the weapon and vice versa.

0
source

Source: https://habr.com/ru/post/1628925/


All Articles