“Enemy”是否未在此范围内宣布?

时间:2011-04-12 22:12:40

标签: c++ include circular-dependency

好的,这就是我的错误:'Enemy'未在此范围内声明。错误在map.h文件中,即使map.h包含enemy.h,如图所示

#ifndef MAP_H_INCLUDED
#define MAP_H_INCLUDED

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "enemy.h"

#define MAX_TILE_TYPES 20

using namespace std;

class Map{
        public:
        Map();
        void loadFile(string filename);
        int** tile;
        int** ftile;
        bool solid[MAX_TILE_TYPES];
        int width;
        int height;
        int tileSize;

        vector<Enemy> enemies;

};

#endif // MAP_H_INCLUDED

这是敌人。

#ifndef ENEMY_H_INCLUDED
#define ENEMY_H_INCLUDED

#include "global.h"
#include "map.h"

class Enemy{
        public:
        Enemy();
        Enemy(float nx, float ny, float nstate);
        void update(Map lv);
        bool rectangleIntersects(float rect1x, float rect1y, float rect1w, float rect1h, float rect2x, float rect2y, float rect2w, float rect2h);
        void update();
        float x;
        float y;
        Vector2f velo;
        float speed;
                float maxFallSpeed;
        int state;
        int frame;
        int width;
        int height;

        int maxStates;
        int *maxFrames;

        int frameDelay;

        bool facingLeft;
        bool onGround;

        bool dead;
        int drawType;
};

#endif // ENEMY_H_INCLUDED

任何人都知道发生了什么以及如何解决这个问题?

3 个答案:

答案 0 :(得分:6)

enemy.h包括map.h

但是,map.h包含enemy.h

因此,如果您包含enemy.h,处理将如下所示:

  • ENEMY_H_INCLUDED已定义
  • 包含global.h
  • 包含map.h
    • 定义了MAP_H_INCLUDED
    • enemy.h包括在内
      • 已定义ENEMY_H_INCLUDED,因此我们跳到文件末尾
    • 类定义了Map
      • 错误,Enemy尚未定义

要解决此问题,请从#include "map.h"移除enemy.h,然后将其替换为转发声明,class Map;

您还需要修改void update(const Map& lv); - 使用const&amp;

并在enemy.cpp

中加入“map.h”

答案 1 :(得分:2)

您的包含中存在循环依赖关系:map.h包含enemy.henemy.h包含map.h

您必须删除循环包含。

答案 2 :(得分:2)

您需要删除其中一个#include语句以打破循环引用。为了允许代码编译,您可以将其中一个包含的类声明为一个简单的定义

class Map;
例如,在Enemy.hpp文件的顶部

,然后在cpp文件中包含标题。

相关问题