C++ 错误 C2065:未声明的标识符

c++ error C2065 : undeclared identifier

本文关键字:标识符 未声明 错误 C2065 C++      更新时间:2023-10-16

可能的重复项:
C++ 未声明的标识符(但它已声明?

当我尝试编译时,我收到错误sprite.h(20): error C2065: 'Component' : undeclared identifier(我也得到了其他几个文件(。下面是sprite.h文件。我一辈子都无法弄清楚是什么导致了这个问题。

#ifndef SPRITE_H
#define SPRITE_H
#include "Image.h"
#include "Rectangle.h"
#include <string>
#include <SDL.h>
#include <vector>
#include "Component.h"
namespace GE2D {
    class Sprite {
    public:
        Sprite();
        Sprite(Image *i);
        Sprite(Image *i, int x, int y);
        Sprite(char *file, bool transparentBg, int x, int y, int w, int h);
        virtual ~Sprite();
        virtual void tick(SDL_Surface *screen, std::vector<Sprite*>* sprites, std::vector<Component*>* components);
        virtual void handleEvent(SDL_Event eve);
        virtual void draw(SDL_Surface *screen);
        void setPosition(int x, int y);
        const Rectangle& getRect() const;
        const Image& getImage() const;
        const Sprite& operator=(const Sprite& other);
        Sprite(const Sprite& other);
    protected:
    private:
        Image image;
        Rectangle rect;
    };
}
#endif

.cpp文件中,tick()定义如下:

void Sprite::tick(SDL_Surface *screen, std::vector<Sprite*>* sprites, std::vector<Component*>* components) {}

tick()应该像现在一样采用两个向量,但也许有更好的方法来解决这个问题?

编辑根据要求,这里也Component.h

#ifndef COMPONENT_H
#define COMPONENT_H
#include "Rectangle.h"
#include "Component.h"
#include "Sprite.h"
#include <vector>
#include <SDL.h>
namespace GE2D {
    class Component {
    public:
        Component();
        virtual ~Component();
        virtual void draw(SDL_Surface *screen) = 0;
        virtual void tick(SDL_Surface *screen, std::vector<Sprite*>* sprites, std::vector<Component*>* components) = 0;
        virtual void handleEvent(SDL_Event eve) = 0;
        const Rectangle& getRect() const;
    protected:
        Component(int x, int y, int w, int h);
    private:
        Rectangle rect;
    };
}
#endif

>Sprite.h包含Component.h,其中包括Sprite.h,给出无法解决的循环依赖关系。

幸运的是,您根本不需要包含标头。每个类只引用指向另一个类的指针,为此,一个简单的声明就足够了:

class Component;