C ++类:带标识符的错误

时间:2015-06-26 09:10:34

标签: c++ class

我在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给我的错误:

有人可以帮我解决这个问题吗?

1 个答案:

答案 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.

Why you need it here, even with the relevant #include directives

An #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.
  • The first line of Player.h is #include "Enemy.h": the file Enemy.h is included.
  • The first line of Enemy.h is #include "Player.h": since the file Player.h has already been included, the directive is ignored.
  • Definition of Enemy
  • Definition of Player
  • Definition of the main function

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