首先,如果我在问题中使用了不正确的术语,我想道歉。我没有接受过任何正式的编程培训。这是我能做的最好的事情来传达这个问题。
我的问题是:
在下面的代码结构中,Inventory 类如何在不将 vector 设置为静态的情况下完全访问 Player 类中的 Items vector ?
-- main.cpp
#include <iostream>
#include <vector>
#include "World.hpp"
#include "Interface.hpp"
int main()
{
World objWorld;
Interface objInterface;
return 0;
}
-- 世界.hpp
#pragma once
#include "Player.hpp"
class World
{
public:
Player objPlayer;
};
-- 播放器.hpp
#pragma once
class Player
{
public:
std::vector<int> Items;
};
-- 界面.hpp
#pragma once
#include "Inventory.hpp"
class Interface
{
public:
Inventory objInventory;
};
-- 库存.hpp
#pragma once
class Inventory
{
public:
// Needs to have complete access to Items, be able to see and modify the vector
};
最佳答案
这不是 C++ 问题,这是面向对象编程的问题。
有很多方法可以做到这一点。但所有这些都涉及不止一个对象一起工作。 Player
必须有对 Inventory
的引用(指针),或者 Inventory
必须有对播放器的引用 - 以某种方式。
这里有一些选项:
你可以在构造函数中传递一个指针(这只是一个简单的例子,请使用共享指针)
class Inventory
{
private:
Player *owner;
public:
Inventory(Player *owner) : owner(owner){}
};
将其作为方法参数传递
class Inventory
{
public:
void drawFor(Player *owner);
};
设置字段值。
class Inventory
{
private:
Player *owner;
public:
void setOwner(Player *owner) {this->owner = owner;}
};
作为旁注,您确定 Player
具有项目 vector 吗?我敢说 Player
可能拥有一个 Inventory
。 Inventory
不仅仅是元素的 vector 。它对元素数量有(可能很复杂)限制,它可以保持影响玩家移动的元素重量,它可以通过添加容器来扩展。所有这些都对 Player
或 NPC
有用。你只需要为 Inventory
关于c++ - 如何访问超出范围的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45459638/