'Enemy' was not declared in this scope?

别等时光非礼了梦想. 提交于 2019-12-24 03:26:20

问题


Okay, so thats my error: 'Enemy' was not declared in this scope.The error is in the map.h file, even though map.h includes enemy.h as shown

#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

And here is enemy.h

#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

Anyone know whats going on and how to fix it?


回答1:


You need to remove one of the #include statements to break the circular reference. To allow the code to compile you can declare one of the included classes as just a simple definition

class Map;

in the top of the Enemy.hpp file, for example, and then include the header in the cpp file.




回答2:


enemy.h includes map.h

but, map.h includes enemy.h

So, if you include enemy.h, the processing will go something like this:

  • ENEMY_H_INCLUDED gets defined
  • global.h is included
  • map.h is included
    • MAP_H_INCLUDED gets defined
    • enemy.h gets included
      • ENEMY_H_INCLUDED is already defined, so we skip to the end of the file
    • class Map gets defined
      • error, Enemy has not been defined yet

to fix this, remove #include "map.h" from enemy.h, and replace it with a forward declaration, class Map;

You will also need to modify void update(const Map& lv); -- use a const&

and include "map.h" in enemy.cpp




回答3:


There is a circular dependency in your includes: map.h is including enemy.h and enemy.h is including map.h

You must remove the circular inclusion.



来源:https://stackoverflow.com/questions/5642237/enemy-was-not-declared-in-this-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!