2014-09-14 2 views
-3

작은 포커 게임을 만들려고합니다. 아래의 코드에는 Game 클래스와 Player 클래스가 있습니다. 게임 클래스는 모든 플레이어를 포함하는 std :: vector를 포함합니다. Player 클래스에는 name 특성이 있습니다. 이제 내 질문은 다음과 같습니다. Player 객체가 포함 된 벡터를 통해 Player의 속성 이름에 어떻게 액세스 할 수 있습니까? 내 문제는 show()라는 아래 코드의 마지막 메서드에서 나타납니다.다른 클래스에서 객체의 속성 가져 오기 C++

도와 주셔서 감사합니다.

//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

하여 플레이어 이름에 액세스 할 수 있습니다 : 당신은 플레이어의 이름을 반환합니다 플레이어 클래스에 대한 방법, 예를 추가해야합니다. 단일 '플레이어'의 이름은 인쇄 할 수 없습니다. 그것이 당신이 알아 내야 만하는 것입니다. 귀하의 질문은 주로 관련성이없는 정보입니다. – juanchopanza

답변

2

플레이어 클래스의 이름 attrbute 개인, 그래서 당신은 다른 클래스에서 직접 액세스 할 수 있기 때문에.

class Player 
{ 
private: 
    std::string name; 

public: 
    std::string getName() const { return name; } 
}; 

그런 다음 당신이 벡터는`Game`을 잊어 버려 잊어 버려

playersVector[i].getName() 
+0

또는'name' 공개. 사적인 이유가없는 것 같습니다. – juanchopanza

관련 문제