我想在我的抽象实体类中存储一个指向主游戏类的指针。
实体.h
#include "Game.h"
class Entity
{
public:
Entity(Game* game);
~Entity(void);
virtual void Draw(float dt) = 0;
virtual void Update(float dt) = 0; // '= 0' means pure virtual function (like 'abstract' in C#)
protected:
Game* m_game; // Missing type specifier error C4430
};
实体.cpp
#include "Entity.h"
Entity::Entity(Game* game)
{
m_game = game;
}
Entity::~Entity(void)
{
}
然后我应该能够实例化一个派生类并将 Game 类引用传递给构造函数,以便将其传递给存储它的基类:
边界.h
#include "Entity.h"
class Boundary : public Entity
{
public:
Boundary(Game* game);
~Boundary(void);
// Override pure virtual functions
void Draw(float dt);
void Update(float dt);
};
Boundary 构造函数然后可以使用引用的 Game 类来将自身添加到列表中:
#include "Boundary.h"
Boundary::Boundary(Game* game) : Entity(game)
{
// Add entity to the main entity list
game->m_entities->push_back(*this);
}
Boundary::~Boundary(void)
{
}
void Boundary::Draw(float dt)
{
// Call the base class as follows (C# equivalent: 'base.Draw(dt)')
//Entity::Draw(dt);
}
void Boundary::Update(float dt)
{
}
这会导致 3 种问题:
game->m_entities->push_back(*this);
错误 C2663:“std::list<_Ty,_Ax>::push_back”:2 个重载对“this”指针没有合法转换
Game* m_game;
在实体.h
错误 C4430:缺少类型说明符 - 假定为 int
list<Entity>* m_entities;
在游戏.h
错误 C2065:“实体”:未声明的标识符
Entity(Game* game);
在实体.h
错误 C2061:语法错误:标识符“游戏”
我想要实现的 C# 等价物是:
public abstract class Entity
{
protected Game game;
public abstract void Draw(float dt);
public abstract void Update(float dt);
}
public class Boundary : Entity
{
public Boundary(Game game)
{
this.game = game;
game.Entities.Add(this);
}
public override void Draw(float dt)
{
}
public override void Update(float dt)
{
}
}
我哪里出错了?
编辑:
Game.h
#include "btBulletDynamicsCommon.h"
//#include "LinearMath\btQuaternion.h"
#include <list>
using namespace std; // Required for list
class Entity; // Forward declaration
class Game
{
public:
list<Entity>* m_entities;
Game(void);
~Game(void);
void init();
void draw(float dt);
void loadContent();
void update(float dt);
private:
class btDefaultCollisionConfiguration* m_collisionConfiguration;
class btCollisionDispatcher* m_dispatcher;
class btDiscreteDynamicsWorld* m_dynamicsWorld;
class btBroadphaseInterface* m_overlappingPairCache;
class btSequentialImpulseConstraintSolver* m_solver;
void exitPhysics();
void initPhysics();
};
编辑2:
我现在剩下的唯一问题是尝试在构造函数中引用游戏:
Boundary::Boundary(Game *game)
: Entity(game) // Initialise base
{
// Add entity to the main entity list
game->m_entities->push_back(*this); // ERROR
}
基类遇到同样的问题
Entity::Entity(Game* game)
: m_game(game) // Initialise members
{
m_game->m_entities->push_back(this); // ERROR here too
}