简体   繁体   中英

Friend has access to friend's member, but can't seem to update friend's member

Within the Dealer class, I declare Player as a friend class. Note that deck is a Dealer member, and I have the following Dealer function:

deque<pair<int, string>> Dealer::deal(int numOfCards){
    deque<pair<int, string>> dealtCards;

    for (int i = 1; i <= numOfCards; i++)
    {       
        dealtCards.push_back(deck.front());
        deck.pop_front(); // once a card is dealt, delete it from the deck
    }

    return(dealtCards);
}

When I call this function directly, for example in main(), the deck is updated appropriately (front cards are deleted). However, when I call this function from the Player class, the Dealer deck member is not updated. For example, I'm expecting this function to update Dealer deck, but it's not:

Player::Player(Dealer dealer, int numOfCards){// deal numOfCards to player
    holeCards = dealer.deal(numOfCards);
}

I don't see what's the difference. Player does have access to Dealer's private member deck, as I can see the holeCards are updated correctly. But for some reason, this constructor is just not performing the pop_front() portion of the deal function. What am I doing wrong? Thank you!

Change

Player::Player(Dealer dealer, int numOfCards)

to

Player::Player(Dealer &dealer, int numOfCards)

If you want to understand more check swap by reference example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM