help with preoproscessor directives

i am trying to make a type from one class carry over to another class and dont know how. i need to get "Hero player" into my Battle class so it can process the players health in a battle along with xp.

as the code is i get this error:

Battle.cpp||In member function 'void Battle::MainBattle()':|
Battle.cpp|5|error: 'player' was not declared in this scope|
||=== Build finished: 1 errors, 0 warnings ===|

Main.cpp
1
2
3
4
5
6
7
8
9
10
11
#include "Main.h"

int main()
{
Hero player;
player.setexp(0);
player.sethealth(50);
std::cout << "player starts with " << player.getexp() << " exp and " << player.gethealth() << " health \n\n";

return 0;
}


Main.h
1
2
3
#include <iostream>
#include "Hero.h"
#include "Battle.h" 


Hero.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "Hero.h"

//get the Heroes health
int Hero::gethealth()
{
    return health;
}
//get the heroes experience
int Hero::getexp()
{
    return exp;
}
//set the heroes health
int Hero::sethealth(int newhealth)
{
    health = newhealth;
    return health;
}
//set the heroes experince
int Hero::setexp(int newexp)
{
    exp = newexp;
    return exp;
}


Hero.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

class Hero
{
    public:
    int getexp();
    int gethealth();
    int sethealth(int);
    int setexp(int);

    private:
    int health;
    int maxhealth;
    int exp;
    int newhealth;
};


Battle.cpp
1
2
3
4
5
6
#include "Battle.h"

void Battle::MainBattle()
{
    std::cout << player.gethealth();
}


Battle.h
1
2
3
4
5
6
7
#include <iostream>

class Battle
{
public:
        void MainBattle();
};
closed account (zb0S216C)
Follow your compiler's errors. Looking at Battle.h, which Battle.cpp includes, no player is ever declared. However, it is declared within Main.cpp, local to main().

Wazzak
Last edited on
Generally, when we want some function to do something with a variable, we pass that variable as a parameter to the function. Read up on functions.
Last edited on
You can pass the Hero object to the function as an argument? Don't know if want it that way.

Battle.cpp
1
2
3
4
5
6
7
#include "Battle.h"
#include "Hero.h"

void Battle::MainBattle(Hero& player)
{
    std::cout << player.gethealth();
}



Battle.h
1
2
3
4
5
6
7
8
9
#include <iostream>

class Hero;

class Battle
{
public:
        void MainBattle(Hero& player);
};
Last edited on
why your header don't have include guard?

TIP:
1
2
3
4
#ifndef HEADER_NAME
#define HEADER_NAME
 //header code...
#endif 


tip2:
DO NOT include headers into other header if not needed.
use forward declaration if possible and include headers into *.cpp file


Topic archived. No new replies allowed.