我的游戏有一个 Player 类,它是一个玩家,由用户控制,它将使用武器。武器类位于不同的头文件中,但包含对玩家的引用,因此它可以告诉玩家类它必须使用什么动画。
现在我的问题是: 似乎我在互相引用时做错了什么。我在两个头文件中都创建了前向减速,但出现错误:“不允许不完整的类型”
我还得到 “无法从 Player* const 转换为 Weapon”
,因为我使用了这个:m_weapon(Weapon(this))
,这是解决问题的尝试问题。
我的文件:
播放器.h
#ifndef PLAYER_H
#define PLAYER_H
#include "DrawableObject.h"
#include "PlayerState.h"
class Weapon;
class Player : public AnimatableObject
{
private:
std::string m_name; //name of the player
States::PlayerState m_state; //state of the player
Weapon &m_weapon;
public:
Player(std::string name):
AnimatableObject("../../Images/PlayerSheet.png",
sf::Vector2i(64,64),sf::Vector2i(8,8)),
m_name(name),
m_weapon(Weapon(this))
{
m_updateTime = 100;
}
//Update the Player
virtual void Update() override;
};
#endif
武器.h
#ifndef WEAPON
#define WEAPON
#include "DrawableObject.h"
class Player;
class Weapon : AnimatableObject
{
protected:
float m_cooldown;
Player *m_user;
public:
Weapon(Player *user):m_cooldown(0.0f),
m_user(user),
AnimatableObject("",sf::Vector2i(0,0),sf::Vector2i(0,0))
{}
Weapon(Player *user, float f):
m_cooldown(f),
AnimatableObject("",sf::Vector2i(0,0),sf::Vector2i(0,0)),
m_user(user)
{}
virtual void Use(){} //Left Click/Trigger
virtual void AltUse(){} //Right Click/Trigger
};
#endif WEAPON
那么如何互相引用和处理头文件呢?
附言。如果有帮助,我将使用 Visual Studio 2012
最佳答案
您的代码存在一些问题:
m_weapon(Weapon(this))
当您这样做时,您正在尝试构建一个新的 Weapon
对象。但在这个阶段,它还没有被定义(只是前向声明)。尝试将构造函数的实现移动到您的 .cpp 文件,其中包含 Weapon.h
文件。
另一个问题是 m_weapon
是对 Weapon
对象的引用。当您执行 m_weapon(Weapon(this))
时,您正在尝试构建一个新对象,传递对它的引用并立即销毁它,因为它是一个临时对象。你不能那样做。
您可以做的是将m_weapon
更改为指针并使用new Weapon(this)
对其进行初始化。然后你必须记住在 Player 的析构函数中销毁它。
在这种情况下,确定哪个对象拥有另一个对象很重要。在这种情况下,Player 将拥有 Weapon 对象,并且有责任管理它(适当时删除)。
关于c++ - 多个类在多个头文件中互相引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22984288/