c++ - 如何访问超出范围的类?

标签 c++ class

首先,如果我在问题中使用了不正确的术语,我想道歉。我没有接受过任何正式的编程培训。这是我能做的最好的事情来传达这个问题。

我的问题是:

在下面的代码结构中,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 可能拥有一个 InventoryInventory 不仅仅是元素的 vector 。它对元素数量有(可能很复杂)限制,它可以保持影响玩家移动的元素重量,它可以通过添加容器来扩展。所有这些都对 PlayerNPC 有用。你只需要为 Inventory

想出一个好的接口(interface)

关于c++ - 如何访问超出范围的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45459638/

相关文章:

PHP - PDO 连接类 - 无法访问

java - 我如何使用 set 和 get 方法为我的程序询问和检索用户输入?

class - 在面向对象编程中,对象的粒度是否有经验法则?

c++ - 结构中的 vector 不会让我 push_back

class - 创建一个不可实例化、不可扩展的类

python - 收集类变量中的所有实例总是不好的吗?

c++ - 约束成员函数和显式模板实例化

c++ - 在 Visual Studio 2008 中使用 Tortoise SVN 和 C++

c++ - 设计一个好的 C++ 包装类来包装多种功能

c++ - 在从 std::variant 继承的类上使用 std::visit - libstdc++ vs libc++