【问题标题】:c++ error C2065 : undeclared identifier [duplicate]c ++错误C2065:未声明的标识符[重复]
【发布时间】:2012-12-28 14:38:11
【问题描述】:

可能重复:
C++ Undeclared Identifier (but it is declared?)

我在尝试编译时收到错误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

【问题讨论】:

  • 显示Component.h的内容
  • 你确定“Component.h”定义了一个名为“Component”的类型吗?
  • @BoPersson,是的,它们似乎是一样的,我该怎么办?
  • @Ceilingbat - 您无需执行任何操作,我们只是将它们链接在一起,以便下一个遇到相同问题的人更容易找到它们。

标签: c++ vector compiler-errors undeclared-identifier


【解决方案1】:

Sprite.h 包含Component.h,其中包含Sprite.h,产生无法解析的循环依赖。

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

class Component;

【讨论】:

  • 但是包含守卫不应该解决这个问题吗?这不就是他们的目的吗?编辑:哦 nvm 我看到了你的答案
  • @Ceilingbat:不,它们只防止多重包含。没有办法在Component之前定义SpriteSprite之前定义Component
  • 声明应该在哪里?
  • @Ceilingbat:在Sprite的定义之前声明Component,在命名空间内,反之亦然。
  • @Ceilingbat 包含守卫只会阻止它无限递归包含。从 Component.h 开始,然后在您的脑海中进行包含。注意 Sprite 上面不会有 Component 的定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 2011-04-16
  • 2011-04-16
  • 2010-12-24
  • 2023-03-04
  • 2011-03-02
  • 2011-12-22
相关资源
最近更新 更多