指向对象的指针数组返回jibberish
Array of pointers to objects returns jibberish
晚上好,
我的任务是创建一个数组来容纳游戏中的所有对象。遗憾的是,所有这些对象都是在不同的地方创建的——手动将它们放入数组会很乏味——事实上,如果它们在创建它们的地方,但引用存储在数组中,我会感觉更好。。指针形式的引用。
所以,这就是我到目前为止所发现的,我已经这样做了,指向对象的每个实例的指针都被添加到构造函数中的数组中,如下所示:
const int GAME_MAX_ENTS = 65536;
class Object
{
public:
static Object* list[GAME_MAX_ENTS];
char type[64] = "ENT_OBJECT";
Object();
~Object();
};
Object::Object()
{
for (int i = 0; i < GAME_MAX_ENTS; i++)
{
if (!list[i])
{
list[i] = this;
break;
}
}
}
Object* Object::list[GAME_MAX_ENTS];
现在,我的问题是——当我试图查看该列表并在与创建对象的范围不同的范围中显示"type"的值时,它会弹出一些无稽之谈——我假设它是随机内存输出。
以下是我试图弹出正确信息的部分:
static void OnRender()
{
//Grid
SDL_RenderClear(renderer);
//Draw objects
for (int i = 0; i < GAME_MAX_ENTS; i++)
{
if (Object::list[i])
{
Object* obj = Object::list[i];
printf("%sn", obj->type);
}
}
[...]
为了让一切尽可能清楚,这里是我创建对象的部分——请注意,Tile只是一个继承自Object:的类
static void Initialize()
{
[...]
Tile tile;
Object obj;
}
我很确定这都是因为我缺乏C++的经验,我只是一个网络开发人员/C#擦洗-不要对我太苛刻^^
看起来您在Initialize()
中创建的对象超出了范围。在C++中,您必须管理自己的内存(当使用指针时)。存储指向对象的指针并不能防止它被销毁。
您需要存储对象的副本,或者使用new
显式创建对象,然后管理指针(或者使用C++智能指针来帮助您管理它们)。
您应该保留指向对象的指针,使它们在构造时自动添加,在销毁时自动删除。这样做的一种方法是有一个观察指针的set
:
// file object.h
namespace game {
struct object // all game objects are derived from this
{
static set<const object*> const&list(); // return list of all objects
virtual draw() const; // example of virtual function
object(); // only ctor: add this to list
object(object const&) = delete; // disable copy ctor of base
virtual ~object(); // dtor: remove this from list
};
}
// file object.cc
#include "object.h"
#include <set>
#include <mutex>
namespace {
std::mutex protect_object_list;
std::set<const object*> object_list;
}
std::set<const object*> const& object::list()
{
return object_list;
}
object::object()
{
std::lock_guard<std::mutex> lock(protect_object_list);
object_list.insert(this);
}
object::~object()
{
std::lock_guard<std::mutex> lock(protect_object_list);
object_list.erase(this);
}
用法可能看起来像
#include "object.h"
namespace game {
struct tile : object
{
void draw() const override;
tile(position const&pos) : object() { /* ... */ }
tile(tile const&t) : object() { /* ... */ }
};
void draw_objects()
{
for(auto const&obj:object::list())
obj.draw();
}
}
通过这种方式,object::list
中的对象通过指针比较进行排序。如果您想要另一个排序,您可能需要使用std::map<size_t,const object*>
,并使用在构造对象时递增的静态计数器作为键。
相关文章:
- 为什么 C++ 中的字符数组返回其项目而不是地址?
- C++ bool 数组返回 1 或 0 以外的值
- C++ ostream 从对象数组返回数据
- 类中的重载运算符 [],因此它可以从模板类中的数组返回对象
- 指向对象的指针数组返回jibberish
- 具有基本结构的结构数组返回错误的答案
- 数组返回乐趣 movie_check()
- C++从字符数组返回类型为T的指针
- C++-将数组返回到主函数,并将数组传递给另一个函数
- C++:如何通过异常处理从越界数组返回值
- 整数数组返回类型
- 从字符串流复制到 char * 数组返回为函数参数
- C++函数从对象数组返回对象的副本.这是默认行为吗?
- 8字节数组返回长(C#到C++)
- 向c#数组返回一个字符数组c++
- 从并行数组返回值,并在以后的函数中使用这些值
- 将c++中的浮点数数组返回给Python
- 如何在gsoap中使字符串数组返回值
- 将两个字符相乘并向数组返回int
- C++套接字 - 从结构数组返回单个地址信息