将类的实例传递到类中

Pass instance of class into Class

本文关键字:实例      更新时间:2023-10-16

我需要将一个类的不同实例传递到该类中,以便我可以在里面访问

Player Player1(Player2);
Player Player2(Player1);

但是,由于尚未创建 P2,因此它不起作用。或者有没有更好的方法在 P2 内部访问 P1?

没错。玩家 1 如何知道玩家 2,因为它不是在创建玩家 1 时创建的。最好在 Player 类中使用 setter 方法。

例子是。

class Player
{
    public:
        Player();
        setPlayer(Player* player)
        {
            otherPlayer = player;
        }
    private:
        Player* otherPlayer;
};

然后你可以称这些为。

Player Player1;
Player Player2;
Player1.setPlayer(&Player2);
Player2.setPlayer(&Player1);

您可以传递稍后将在其中创建 Player2 的指针:

/*** class declaration ***/
class Player
{
private:
  class Player **ref; // pointer to pointer of reference Player class
  bool all_done;      // flag to indicate whether the whole initialization procedure is finished
public:
  Player1(class **RefPtr);    // constructor declaration
  void DoRemainingInit();     // if necessary, perform remaining initialization steps
}

/*** class method definitions ***/
Player::Player(class **RefPtr):
    ref(NULL), all_done(false)
{
  // ...
  if (RefPtr == NULL)
  {
    // pointer invalid -> do some error handling here
    return;
  }
  ref = RefPtr;
  if (*ref == NULL)
  {
    // pointer is valid, but doesn't yet point to another class instance -> try to access it later by calling DoRemainingInit()
    // ...
  }
  else
  {
    // pointer is valid and should point to an existing object (depends on whether RefPtr was properly initialized with NULL outside) -> do your stuff here
    all_done = true;
    // ...
  }
}
void Player::DoRemainingInit()
{
  if (all_done)
  {
    // nothing to be done here -> return immediately
    return;
  }
  if (*ref == NULL)
  {
    // reference object not yet existent -> possibly treat as error?
    // ...
  }
  else
  {
    // reference object is now existent -> do the same stuff as in the constructor's "else" branch
    all_done = true;
    // ...
  }
}

/*** creating the objects ***/
class *Player1 = NULL;  // WARNING: MUST be set to NULL initially, otherwise the check inside Player's constructor won't work correctly
class *Player2 = NULL;  // WARNING: MUST be set to NULL initially, otherwise the check inside Player's constructor won't work correctly
Player1 = new Player(&Player2);
Player2 = new Player(&Player1);
Player1->DoRemainingInit();
Player2->DoRemainingInit();
return; // WARNING: "ref" inside both classes is not valid any more, once we return here!

请注意,"ref"属性实际上指向"Player2"指针本身,因此一旦"Player2"指针的范围留在Playeyou内部,也不能立即在Player1的构造函数中Player2,则不再有效。您可能还希望通过使引用恒定来限制对引用的访问。

另请注意,上面的代码是示例代码,因此缺乏一些基本的安全检查(例如,我们不知道"new"是否能够实际创建一个类实例)。