class - C++ Classes: errors with identifiers -


i've project in c++ 2 classes.

main.cpp:

#include <iostream> #include <conio.h> #include "player.h" #include "enemy.h"  using namespace std;  int main() { const int starthealth = 100, startarmor = 50, startenemyhealth = 70, startweapon = 1;  player *mick = new player(starthealth, startarmor, startweapon); enemy *mon = new enemy(startenemyhealth);  cout << "start!" << endl; cout << mick->health << " : " << mick->armor << endl;  cout << "enemy attacks!" << endl; mon->attack(mick);  cout << "damage taken!" << endl; cout << mick->health << " : " << mick->armor << endl;  cout << "you attack!" << endl; mick->attack(mon);  cout << "enemy's health!" << endl; cout << mon->health << endl;  _getch(); return 0; }  

player.h

#pragma once #include "enemy.h"  class player { public: int health, armor; int weapon;  public: player(const int _starthealth, const int _startarmor, const int         _startweapon); ~player(); void attack(enemy *_attackedenemy); }; 

enemy.h

#pragma once #include "player.h"  class enemy { public: float speed; int damage; int health;  public: enemy(const int _startenemyhealth); ~enemy(); void attack(player *_attackedplayer); void refresh(enemy *_enemytorefresh); }; 

the errors these ones:

meanwhile, these errors codeblocks gives me:

can me issue?

the problem player class refers enemy class, refers player class:

class enemy {     void attack(player *_attackedplayer); } class player {     void attack(enemy *_attackedenemy); } 

what need forward declaration, inform compiler particular class exists, without telling information class.

here can add following line in file enemy.h, before definition of enemy class:

class player; 

look @ this question see can or cannot forward declarations.

why need here, relevant #include directives

an #include directive instruction preprocessor tells replace directive included file. #pragma once directive ensures file won't included more once each translation unit.

in main.cpp, here's going on:

  • #include "player.h": file player.h included.
  • the first line of player.h #include "enemy.h": file enemy.h included.
  • the first line of enemy.h #include "player.h": since file player.h has been included, directive ignored.
  • definition of enemy
  • definition of player
  • definition of main function

as can see, includes, @ time of definition of class enemy, compiler doesn't know class player exists yet. reason why absolutely need forward declaration here.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -