Help with reference pass in C ++?


Hi, I'm "doing" a game like practice ... I need to pass by reference a player data type to a function in the enemy class, I can not directly add the "jugador.h" in "enemy.h" since it's included in another header, that's why I need to declare it by ifndef .. here the code

#ifndef JUGADOR_H
#define JUGADOR_H

class Jugador;

class Enemy



    sf::Texture texturaEnemy;
    sf::Sprite spriteEnemy;
    sf::IntRect rectEnemy;
    sf::Clock clock, frame;
    sf::Time time;
    sf::Text vidaTexto;
    sf::Font vidaFuente;
    bool repetir = true;
    bool movimiento = true;
    int speed = 50;
    int orientacion = 0;
    int balas = 0;
    float x = 0;
    float y = 0;
    float delta;


    void Inicializar();
    void EnemyMovement(Jugador &jugador);
    void Movement();
    void EnemyDraw(sf::RenderWindow &window);
    void Collision(Jugador &jugador);
    void UpdateEnemy(sf::RenderWindow &window, Jugador &jugador);


As you can see use #ifndef to include the player class, below you will see the methods of the class enemy to which I am going by reference the type of data player &jugador , and here is where I have the problem :

    void Enemy::EnemyMovement(Jugador &jugador) {

        time = clock.restart();
        delta = time.asSeconds();

        int diferenciaX = spriteEnemy.getPosition().x - error;

        if (diferenciaX > -1 && diferenciaX < 1) {
            movimiento = true;
        else {
            movimiento = false;

        if (spriteEnemy.getPosition().y < error && movimiento) {
   = 0;
            spriteEnemy.setPosition(spriteEnemy.getPosition().x, spriteEnemy.getPosition().y + speed * delta);
            if (frame.getElapsedTime().asSeconds() > 0.2f) {

at the time of writing player. I do not get the variables that I have in the player class to be able to modify them from this method ... if anyone knows please thanks

asked by Shum 25.01.2018 в 04:17

1 answer


I can not directly add the "player.h" to the "enemy.h" because it is included in another header

The header does not need to know the implementation of Jugador since the class Enemy :

  • does not have a member variable of type Jugador .
  • does not have inline functions that access functions or variables of class Jugador .
  • does not inherit from Jugador

Then the declaration forward that you do in "enemy.h" is an example of how things should be done in C ++.

However, in the cpp you need to access Jugador functions and that is what is giving you problems ... the solution is as simple as putting:

#include "jugador.h"

... in "enemy.cpp" .

The cpp is not going to suffer the problem of crossover includes from the header since no one includes a cpp in another, so in the cpp should not have problems when putting as many includes as necessary.

answered by 25.01.2018 в 07:43