Pregunta

My game has a Player class which is a player, controlled by the user and it will wield a weapon. The weapon class is in a different header file but contains a reference to the player, so it can tell the Player class what animation it has to use.

Now my question: It seems that im doing something wrong with referencing to eachother. I have created a forward decleration in both header files, but i get an error: "incomplete type not allowed"

I also get "cannot convert from Player* const to Weapon" because i use this: m_weapon(Weapon(this)), that was a tryout to solve the problem.

my files:

Player.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

Weapon.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

So how do i refer to eachother and dealing with the header files?

PS. im using Visual Studio 2012 if it helps

¿Fue útil?

Solución

There are a few problems with your code:

m_weapon(Weapon(this))

When you do it, you're trying to construct a new Weapon object. But at this stage, it has not been defined yet (only forward declared). Try moving the constructor's implementation to your .cpp file, where you have included the Weapon.h file.

Anothre problem is that m_weapon is a reference to a Weapon object. When you do m_weapon(Weapon(this)), you're trying to contruct a new object, pass a reference to it and immediately destroy it, as it's a temporary. You can't do that.

What you can do is change m_weapon to be a pointer and initialise it with new Weapon(this). You then have to remember to destroy it in Player's destructor.

I this scenario it is important to establish which object owns the other. I this case Player would own the Weapon object and it would be it's duty to manage it (delete when appropriate).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top