从另一个类C++中获取对象的属性

Get attribute of an object from another class C++

本文关键字:取对象 属性 获取 另一个 C++      更新时间:2023-10-16

我正在尝试制作一个小扑克游戏。在下面的代码中,我有一个Game类和一个Player类。游戏类包含一个std::向量,其中包含所有玩家。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?
    }
}

因为Player类的名称属性是私有的,所以您不能直接从另一个类访问它。您应该向Player类添加一个方法,该方法将返回玩家的名称,例如:

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

然后你可以通过访问玩家名称

playersVector[i].getName()