我在弄清楚如何访问嵌套类之外的变量时遇到问题



嵌套类不能访问类外的非静态元素


嵌套类有问题,正如我提供的代码所示,已经声明了2个类,嵌套类Entity在类Game的私有字段内,出于某种原因,嵌套类不允许我访问map_info之外的变量。我只找到了一个解决方案,它涉及到在实体类中创建一个Game类的实例。


class Game
{
private:
std::string map_info;

class entity
{
protected:
double x, y, z;
public:
};
class player : public entity
{
private: std::string name;
player(std::string _name) : name(_name) {};
void check()
{
/*
this is the portion of the code that i'm having problem with
the error: "a nonstatic member reference must be relative to a specific object"
*/
if (map_info != 'none')
{
// do stuff
}
}
};
public:
std::string Getmap() { return map_info; }
Game() //constructor
{
// does stuff
}
};

这是我尝试做的事情

  1. 将map_info声明为静态类型(不能解决问题)
  2. 在嵌套类中声明游戏类的实例

我在这里搜索了同样的问题,但结果不适合我的原始代码,但是可能有一个轻微的机会,我错过了一些东西,如果是这样,请发送链接。

这是我在这个网站的第一个问题,所以给尽可能多的反馈,即使是最轻微的赞赏!谢谢!

这不是你想要的。嵌套类只是游戏类的类成员,如果它是公共的,可以作为Game::NestedName访问,如果它是私有的,则不能在非类中访问。例如

#include <vector>
class Game
{
public:
Game(){};
void spawnNewPrivateEntity(double x, double y, double z)
{
private_entities.push_back(PrivateEntity{x, y, z}); //access to private member PrivateEntity is ok
}
struct PublicEntity { double x, y, z; }; //public nested struct, can be accessed from everywhere
void spawnNewPublicEntity(PublicEntity entity)
{
public_entities.push_back(entity);
}
private:
struct PrivateEntity { double x, y, z; };   //private nested struct, can be used only inside this class or friend members
std::vector<PrivateEntity> private_entities = {};
std::vector<PublicEntity> public_entities = {};
}

int main()
{
auto en = Game::PublicEntity{0.0, 9.0, 1.9}; //works
auto en2 = Game::PrivateEntity{0.0, 0.0, 0.0}; //doesn't work: this struct is private member of Game class
} 

你可以这样写:

class Game
{
public:
Game(std::string map_info): map_info(map_info)
{};
std::string getMapInfo() { return map_info; }
private:
std::string map_info;
};
class Entity
{
public:
Entity(Game *game): game(game)
{};
void check()
{
if (game->getMapInfo() != "none") { /*some code*/ }
};
private:
Game *game;
}

最新更新