我正在努力打一场扑克游戏。在下面的代码中,我有一个Game类和一个Player类。游戏类包含一个std :: vector,其中包含所有玩家。 Player类具有name属性。现在我的问题如下:如何通过包含Player对象的向量访问Player的属性名称?我的问题出现在下面代码的最后一个方法中,名为show()。
感谢您的帮助!
//Player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <iostream>
#include "Card.h"
class Player
{
public:
Player();
Player(std::string n, double chipsQty);
private:
const std::string name;
double chipsAmount;
Card cardOne;
Card cardTwo;
};
#endif PLAYER_H
//Player.cpp
#include "Player.h"
Player::Player(){}
Player::Player(std::string n, double chipsQty) : name(n), chipsAmount(chipsQty)
{}
//Game.h
#ifndef GAME_H
#define GAME_H
#include "Player.h"
#include <vector>
class Game
{
public:
Game();
Game(int nbr, double chipsQty, std::vector<std::string> vectorNames);
void start();
void show();
private:
std::vector<Player> playersVector;
int nbrPlayers;
};
#endif GAME_H
//Game.cpp
#include "Game.h"
#include "Player.h"
Game::Game(){}
Game::Game(int nbr, double chipsQty, std::vector<std::string> vectorNames) :nbrPlayers(nbr)
{
for (int i = 0; i < vectorNames.size(); i++)
{
Player player(vectorNames[i], chipsQty);
playersVector[i] = player;
}
}
void Game::start(){};
void Game::show()
{
for (int i = 0; i < playersVector.size(); i++)
{
std::cout << playersVector[i] //Why can't I do something like playersVector[i].name here?
}
}
答案 0 :(得分:3)
因为Player类的名称属性是私有的,所以您无法直接从另一个类访问它。您应该向Player类添加一个方法,该方法将返回播放器的名称,例如:
class Player
{
private:
std::string name;
public:
std::string getName() const { return name; }
};
然后您可以通过
访问播放器名称playersVector[i].getName()