How to use another classes member variables in c++?
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.
Pass name as a parameter to
display()
function. (You are callingdisplay()
from within a member function ofPlayer
, right? If not, you'll also need to add a public accessor method toPlayer
for getting its name.)Pass a reference to the owining
Player
toScorecard
object (e.g. via constructor) and store it withinScorecard
. Add a public accessor menthod toPlayer
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;
};
精彩评论