从另一个类C++中获取对象的属性
Get attribute of an object from another class C++
我正在尝试制作一个小扑克游戏。在下面的代码中,我有一个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()
相关文章:
- 类对象属性是否可以调用返回属性应具有的值的方法C++?
- 对象属性同级访问
- 迭代 Napi::对象属性(键)在 Node.js C++ N-API 中
- 是否可以在C++(17)中捕获某些对象属性的破坏性赋值事件
- 分配以下对象属性在哪里
- sutex作为对象属性和对象的向量
- C++ - 在类中包含不是类对象属性的变量是否是一种不好的做法
- 根据对象属性从列表中删除对象
- 将对象属性替换为列表
- 查找对象属性是否位于对象向量C++中
- 未知EABI对象属性44
- 按矢量中的对象属性合并排序
- 如何访问带有静态回调的对象属性
- c++中对象属性的内存分配
- 为什么对象属性的值在 c++ 中将其指针添加到映射后返回零
- 如何检查对象属性更新是否存在 std::map 键,否则插入一个新键?
- 从ASP.NET应用程序查询Active Directory对象属性将返回旧结果
- 性能对象属性与范围变量
- 无法访问对象属性
- 如何从对象方法中访问对象属性