'Enemy'没有在此范围内声明?

'Enemy' was not declared in this scope?

本文关键字:范围内 声明 Enemy      更新时间:2023-10-16

好吧,这就是我的错误:'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

这里是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

有谁知道发生了什么以及如何修复它吗?

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被定义
      • 错误,敌人尚未定义

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

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

并在enemy.cpp

中包含"map.h"

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

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

,然后在cpp文件中包含头文件

在include中有一个循环依赖:map.h包含enemy.h, enemy.h包含map.h

您必须删除圆形包含