我在C ++中有一个包含2个类的项目。
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);
};
我得到的错误是这些错误:
同时,这些是CodeBlocks给我的错误:
有人可以帮我解决这个问题吗?
答案 0 :(得分:2)
The problem is that your Player
class refers to your Enemy
class, which also refers to your Player
class:
class Enemy
{
void Attack(Player *_attackedPlayer);
}
class Player
{
void Attack(Enemy *_attackedEnemy);
}
What you need is forward declaration, to inform the compiler that a particular class exists, without telling it any information about this class.
Here you can add the following line in the file Enemy.h
, before the definition of the Enemy
class:
class Player;
Look at this question to see what you can or cannot do with forward declarations.
#include
directivesAn #include
directive is basically an instruction for the preprocessor that tells it to replace the directive by the included file. The #pragma once
directive ensures that the file won't be included more than once for each translation unit.
In Main.cpp, here's what is going on:
#include "Player.h"
: the file Player.h
is included.Player.h
is #include "Enemy.h"
: the file Enemy.h
is included.Enemy.h
is #include "Player.h"
: since the file Player.h
has already been included, the directive is ignored.Enemy
Player
main
functionAs you can see, even with the includes, at the time of the definition of the class Enemy
, the compiler doesn't know that a class Player
exists yet. This is the reason why you absolutely need a forward declaration here.