将类的实例传递给Class

时间:2015-04-27 06:34:00

标签: c++ class

我需要将一个类的不同实例传递给该类,以便我可以在内部访问

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

然而,由于P2尚未创建,但它无法正常工作。或者在P1内部有更好的方法来访问P2吗?

2 个答案:

答案 0 :(得分:1)

完全。 Player1如何知道Player2,因为它不是在Player1创建时创建的。最好在Player类中使用setter方法。

示例是。

class Player
{
    public:
        Player();

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

然后你可以把它们称为。

Player Player1;
Player Player2;

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

答案 1 :(得分:1)

您可以传递稍后将创建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”是否能够实际创建类实例)。