从另一个cpp文件更改结构内部、映射键内部的变量 我是C++新手,所以我不确定我是不是走对了,但我的问题是:
如何从另一个.cpp文件访问和更改在映射中的结构中定义的变量 my.h文件的一部分:从另一个cpp文件更改结构内部、映射键内部的变量 我是C++新手,所以我不确定我是不是走对了,但我的问题是:,c++,dictionary,struct,C++,Dictionary,Struct,如何从另一个.cpp文件访问和更改在映射中的结构中定义的变量 my.h文件的一部分: struct-Borough{ std::string name=“”; int num_players=0; 自治区(std::string n):名称(n){ 友元内联布尔运算符
struct-Borough{
std::string name=“”;
int num_players=0;
自治区(std::string n):名称(n){
友元内联布尔运算符<(const-Borough&lhs,const-Borough&rhs){return(lhs.name
和(部分)player.cpp文件:
#包括
#包括
#包括“player.h”
void Player::move(){
std::string current_loc=get_location();
std::coutstd::map
的键类型始终为const
,因为以可能更改其在映射(树)中的正确位置的方式修改键是错误的
但唯一重要的部分是影响地图中位置的部分。std::map
无法知道这一点,但在您的案例中,一个自治区的比较只涉及其名称,而不涉及num\u玩家
解决此问题的最简单方法是将num_players
标记为mutable
:
mutable int num_players = 0;
然后,即使在const-Borough
中,您也可以修改此值。只要您的Borough比较器不依赖于num\u玩家,它不会损害任何东西
#include <iostream>
#include <stack>
#include "player.h"
void Player::move() {
std::string current_loc = get_location();
std::cout << "\nWhere do you want to move to?" << std::endl;
display_branches(current_loc);
std::string selected_location;
std::getline(std::cin, selected_location);
// verification and placement of player:
if (verify_location(current_loc, selected_location)) {
set_location(selected_location);
// HERE IS WHERE I WANT TO MAKE Borough::num_players++;
std::cout << m_graph.walk.find(selected_location)->first.num_players << " <-- That's the number of players.\n";
}
}
mutable int num_players = 0;