我正在尝试用C ++开发游戏。出于某种原因,我无法访问和更新其他变量作为类的成员公共函数中的私有成员变量的值。为什么会这样?提到的变量是前缀为m_
的变量。这是C ++中不允许的吗?我以为这是允许的!
Player.cpp
#include "Player.h"
#include "lib/json.hpp"
using namespace std;
void Player::createPlayer(std::string name, std::string playerFilePath)
{
m_name = name;
m_playerFilePath = playerFilePath;
json j;
j["name"] = m_name;
j["health"] = 100;
j["levelOn"] = 1;
j["damageDone"] = 10;
std::string dataString = j.dump();
std::string filename = playerFilePath + m_name + ".json";
std::ofstream out(filename);
out << dataString;
out.close();
cout << "Savegame file " << filename << " created" << endl;
}
void Player::loadPlayerData(std::string playerFilePath)
{
std::ifstream t(playerFilePath);
std::string str ((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
auto j = json::parse(str);
m_name = j["name"];
m_health = j["health"];
m_levelOn = j["levelOn"];
m_damageDone = j["damageDone"];
cout << "Player data loaded" << endl;
}
void Player::levelUp()
{
m_levelOn++;
m_health += 10;
m_damageDone += 5;
}
void savePlayerData()
{
std::ifstream t(m_playerFilePath);
std::string str ((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
auto j = json::parse(str);
j["name"] = m_name;
j["health"] = m_health;
j["levelOn"] = m_levelOn;
j["damageDone"] = m_damageDone;
std::string stringToWrite = j.dump();
std::string filename = m_playerFilePath + m_name + ".json";
std::ofstream out(filename);
out << stringToWrite;
out.close();
cout << "Game saved" << endl;
}
Player.h
#pragma once
#ifndef PLAYER_H
#define PLAYER_H
#include <fstream>
#include "Enemy.h"
#include <iostream>
#include <streambuf>
#include "lib/json.hpp"
using json = nlohmann::json;
class Player {
private:
int m_health;
int m_damageDone;
int m_levelOn;
std::string m_playerFilePath;
std::string m_name;
public:
void createPlayer(std::string name, std::string playerFilePath);
void dealDamage();
void takeDamage();
void levelUp();
std::string getPlayerFilePath();
void loadPlayerData(std::string playerFilePath);
void savePlayerData();
};
#endif
g ++错误消息
Player.cpp: In function ‘void savePlayerData()’:
Player.cpp:53:21: error: ‘m_playerFilePath’ was not declared in this scope
std::ifstream t(m_playerFilePath);
^
Player.cpp:59:17: error: ‘m_name’ was not declared in this scope
j["name"] = m_name;
^
Player.cpp:60:19: error: ‘m_health’ was not declared in this scope
j["health"] = m_health;
^
Player.cpp:61:20: error: ‘m_levelOn’ was not declared in this scope
j["levelOn"] = m_levelOn;
^
Player.cpp:62:23: error: ‘m_damageDone’ was not declared in this scope
j["damageDone"] = m_damageDone;
^
Player.cpp:66:28: error: ‘m_playerFilePath’ was not declared in this scope
std::string filename = m_playerFilePath + m_name + ".json";
答案 0 :(得分:3)
函数savePlayerData
不属于Player
类。在Player::
功能之前插入savePlayerData
。