开发者

How to use another classes member variables in c++?

开发者 https://www.devze.com 2023-02-02 11:58 出处:网络
I\'m currently programming a Yahtzee game, and I\'m having trouble with some of my classes I have two classes, Player, and Scorecard.

I'm currently programming a Yahtzee game, and I'm having trouble with some of my classes

I have two classes, Player, and Scorecard.

class Player {
  private:
    string name;
    Scorecard scorecard;
开发者_StackOverflow社区};


class Scorecard {
  public:
    void display() {
      //...
    }
};

(All the classes have the appropriate getters and setters)

I'd like the scorecard class to be able to display the name of the player to the user. Is there any way that can be done?


I would not have Scorecard print the Player's name. A player has-a scorecard. A scorecard does not have a a player.

The Player class should have a display method that displays the player's name followed by the score card:

class Player
{
  private:
     string name;
     Scorecard scorecard;

  public:
    void display(void)
    {
        cout << "Player name: " << name << endl;
        scorecard.display();
    }
};

Also, since Player contains a Scorecard, you should declare the Scorecard class before class Player:

class Scorecard
{
 /*... */
};

class Player
{
 /* ... */
};


You have to somehow give Scorecard the instance of player. Also, Player needs either a public getter or make name public.


The best way to do that is to add a public accessor method to Player that returns either a copy or constant reference to Player::name.


There are several options.

  1. Pass name as a parameter to display() function. (You are calling display() from within a member function of Player, right? If not, you'll also need to add a public accessor method to Player for getting its name.)

  2. Pass a reference to the owining Player to Scorecard object (e.g. via constructor) and store it within Scorecard. Add a public accessor menthod to Player for getting its name.

Personally, I like (1) better, because it allows to minimize dependencies between Player and Scorecard classes.


You could add a PlayerName property to the Scorecard, and then it will be able to store a name. then the display() function will get the name as a parameter


Typically, I'd tell the Scorecard about the Player that owns it:

class Scorecard;

class Player {
  public:
    explicit Player(const string& name_): name(name_), scorecard(*this) {}
    const string& Name(oid) const { return name; }
  private:
    string name;
    Scorecard scorecard;
};

class Scorecard {
  public:
    Scorecard(Player& player_): player(player_) {}
    void display() {
      cout << player.Name() << endl;
      //...
    }
  private:
    Player& player;
};
0

精彩评论

暂无评论...
验证码 换一张
取 消