【问题标题】:'Enemy' was not declared in this scope?“敌人”没有在这个范围内声明?
【发布时间】:2017-10-13 04:11:51
【问题描述】:

好的,这就是我的错误:'Enemy' 未在此范围内声明。错误出现在 map.h 文件中,即使 map.h 包含如图所示的敌人.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

这里是敌人.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

有人知道发生了什么以及如何解决吗?

【问题讨论】:

  • 出现此错误时正在编译哪个源文件(.cpp、.c、.cc 等...)?它看起来像什么?

标签: c++ include circular-dependency


【解决方案1】:

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 已经定义,所以我们跳到文件末尾
    • 类映射被定义
      • 错误,尚未定义敌人

要解决此问题,请从 enemy.h 中删除 #include "map.h",并将其替换为前向声明 class Map;

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

并在enemy.cpp中包含“map.h”

【讨论】:

    【解决方案2】:

    您需要删除#include 语句之一以中断循环引用。为了让代码能够编译,您可以将包含的类之一声明为只是一个简单的定义

    class Map;
    

    例如,在 Enemy.hpp 文件的顶部,然后在 cpp 文件中包含标头。

    【讨论】:

      【解决方案3】:

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

      您必须删除循环包含。

      【讨论】:

        猜你喜欢
        • 2015-10-03
        • 1970-01-01
        • 2018-07-12
        • 1970-01-01
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        • 2011-06-12
        相关资源
        最近更新 更多