How to use one object method to update another object attribute?

I have three classes (C ++): Player, Hand and Card.

The player has a member, a hand that holds the Hand. It also has a getHand () method that returns the contents of the hand.

Hand Player::getHand() {
    return hand;
}

The hand has an addCard method (Card c), which adds a card to the hand.

I want to do this:

player1.getHand () addCard (s) ;.

but that will not work. It does not throw errors, therefore does something. But if I examine the contents of player’s hand1, a card will not be added.

How can I make this work?

+3
source share
8 answers

If getHand () does not return the link, you will have problems.

+1
source

If getHand () returns a value, you are changing the copy of the hand, not the original.

+2

Player.addCardToHand() , . , , , .

+1

. "player1.getHand() → addCard (c)". , , , .

+1

, .

Hand &Player::getHand() {
    return hand;
}

addCard() .

+1

getHand()? Hand & ?

0

, , , .

​​, .

  private:
    Hand(const Hand& rhs);
    Hand& operator=(const Hand& rhs);
0

getX() x, . , "getX" , "getX", X.

, . :

  • getMutableHand, ( ). , , , , , , .
  • Make Player a subclass of the hand , so anything that manipulates the hand also works directly on the Player. Intuitively, you could say that the Player is not a hand, but functionally they have the right relationship: each player has only one hand, and it seems that you want to have the same access to the Hand through the player, since you will be directly.
  • Directly promoting methods addCard for your class Player.
0
source

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


All Articles