我的游戏有一个Player类,它是一个由用户控制的玩家,它将使用武器。武器类位于另一个头文件中,但包含对玩家的引用,因此它可以告诉玩家类必须使用哪种动画。

现在我的问题是:
我似乎在互相参考时做错了事。我在两个头文件中都创建了一个前向清除,但出现错误:“不允许使用不完整的类型”

我也得到"cannot convert from Player* const to Weapon",因为我使用的是m_weapon(Weapon(this)),这是解决问题的一种尝试。

我的文件:

播放器

#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


武器

#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


那么,我该如何互相参考并处理头文件?

PS。我使用Visual Studio 2012,如果有帮助

最佳答案

您的代码存在一些问题:

m_weapon(Weapon(this))


当您这样做时,您正在尝试构造一个新的Weapon对象。但是在此阶段,它尚未定义(仅向前声明)。尝试将构造函数的实现移动到包含Weapon.h文件的.cpp文件中。

另一个问题是m_weapon是对Weapon对象的引用。当您执行m_weapon(Weapon(this))时,您试图构造一个新对象,传递对它的引用并立即销毁它,因为它是临时的。你不能那样做。

您可以做的是将m_weapon更改为指针,并使用new Weapon(this)对其进行初始化。然后,您必须记住在Player的析构函数中销毁它。

在这种情况下,重要的是确定哪个对象拥有另一个对象。在这种情况下,玩家将拥有武器对象,并且有责任对其进行管理(在适当时删除)。

关于c++ - 多个类在多个头文件中相互引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22984288/

10-10 05:17