0

派生クラスを指すPlayerメンバー変数を持つクラスがあります。Creature *characterElf : public Creature

Playerオブジェクトを宣言して、そのメンバーの 1 つを にポイントさせ、情報を取得できるようにしたいと考えていElfます。

データ メンバーは非公開にする必要があることは理解していますが、これは特殊なケースですか、それとも関数Elfからメンバーから情報を取得するにはどうすればよいですか?main

void Player::set_character(Creature &c)
{
  character = &c;
}

...
Player me;
Elf me_elf;
me.set_character(me_elf);
4

2 に答える 2

2

これは、次のパブリック メソッドを介して行うことができますPlayer

class Creature
{
 public:
  virtual void hello() const = 0;
};

class Player{
 public:
  void hello() const { charatcer->hello(); }
  // other methods as before
 private:
  Creature* character;
};
于 2013-05-18T07:33:17.340 に答える
1

if you have a "has a" relationship, you'll have to use wrapper functions to access the data.

if you have a "is a" relationship, you'll be able to access the data if the data is "protected". Without any other troubles. Having protected allows the derived class to access the data.

于 2013-05-18T07:36:30.830 に答える