我有 2 个(不完整的)类,Level 和 Object,在不同的文件中,看起来像这样
Object.h:
#pragma once
#include "Core.h"
class Object
{
public:
Object(const Hitbox &hBox_, const Vector2& position_ = Vector2{0, 0}, const Vector2& velocity_ = Vector2{ 0, 0 });
virtual Hitbox getHitbox();
virtual void update();
virtual void draw();
virtual void drawHbox(const SDL_Color& color = SDL_Color{255, 0, 0, 255});
static Core* core;
protected:
Vector2 position;
Vector2 velocity;
Hitbox hBox;
};
级别.h:
#pragma once
#include "Object.h"
class Level
{
public:
Level(const Vector2 &size_);
void proceed();
bool checkStaticCollision(Object* self);
Object* checkBulletCollision(Object* self);
protected:
std::vector<std::shared_ptr<Object>> objects;
Vector2 size;
};
Level 保留所有对象,对象可以做一些独立的事情,比如绘制自己或接收输入,但对象也必须相互交互,并做一些诸如碰撞、创建和移除自我、发射粒子等级别的事情。我让 Object 可以访问 Level?不完整的类型没有提供所需的功能,所以我不能只在 Object.h 中使用 class Level;
,我不能简单地保留指向所需函数的指针,因为它们是类方法,如果我没有 void* 保留它会很棒。< /p>
答案 0 :(得分:0)
不确定这是否是最好的解决方案,但是,感谢@PeteBecker,我添加了(并且也发现了,呵呵)包含守卫,所以现在看起来像这样:
Object.h:
#include "Core.h"
#ifndef OBJECT_H_
#define OBJECT_H_
#include "Level.h"
class Level;
class Object
{
public:
Object(Level* level_, const Hitbox &hBox_, const Vector2& position_ = Vector2{0, 0}, const Vector2& velocity_ = Vector2{ 0, 0 });
virtual Hitbox getHitbox();
virtual void update();
virtual void draw();
virtual void drawHbox(const SDL_Color& color = SDL_Color{255, 0, 0, 255});
static Core* core;
protected:
Vector2 position;
Vector2 velocity;
Level *level;
Hitbox hBox;
};
#endif
级别.h:
#include "Core.h"
#ifndef LEVEL_H_
#define LEVEL_H_
#include "Object.h"
class Object;
class Level
{
public:
Level(const Vector2 &size_);
void proceed();
bool checkStaticCollision(Object* self);
Object* checkBulletCollision(Object* self);
protected:
std::vector<std::shared_ptr<Object>> objects;
Vector2 size;
};
#endif