C++ 错误C2504:基类未定义

C++ 错误C2504:基类未定义,c++,class,inheritance,header,C++,Class,Inheritance,Header,我以前曾多次遇到过这个错误,最终找到了解决方案,但这一次让我难堪。我有一个由类“Player”继承的类“Mob”。这是Mob.h: #pragma once #include "PlayState.h" #include "OmiGame/OmiGame.h" #include "resources.h" class PlayState; class Mob { private: int frames; int width; int height; int t

我以前曾多次遇到过这个错误,最终找到了解决方案,但这一次让我难堪。我有一个由类“Player”继承的类“Mob”。这是Mob.h:

#pragma once
#include "PlayState.h"
#include "OmiGame/OmiGame.h"
#include "resources.h"

class PlayState;

class Mob
{
private:
    int frames;
    int width;
    int height;
    int time;

    sf::Texture textureL;
    sf::Texture textureR;
    Animation animationL;
    Animation animationR;
    AnimatedSprite sprite;
    bool moveLeft;
    bool moveRight;
    bool facingRight;

public:
    void createMob(std::string l, std::string r, int frames, int width, int height, int time, int x, int y);

    void updateMob(omi::Game *game, PlayState *state);
    void drawMob(sf::RenderTarget &target);

    void setLeft(bool b) { moveLeft = b; }
    void setRight(bool b) { moveRight = b; }
    bool isLeft() { return moveLeft; }
    bool isRight() { return moveRight; }

    sf::Vector2f getPosition() { return sprite.getPosition(); }
};
这是Player.h,到目前为止非常简单:

#pragma once
#include "OmiGame/OmiGame.h"
#include "PlayState.h"
#include "Mob.h"
#include "resources.h"

class PlayState;
class Mob;

const int playerFrames = 8;
const int playerWidth = 16;
const int playerHeight = 48;
const int playerTime = 50;
const int playerX = 200;
const int playerY = 200;

class Player : public Mob
{ //the error occurs at this line//
public:
    Player();
    void update(omi::Game *game, PlayState *state);
    void draw(sf::RenderTarget &target);
};
正如你可能猜到的,这是一个错误:

error C2504: 'Mob' : base class undefined   player.h

我已经转发了声明的mob,我希望已经修复了任何循环依赖项。有人能帮我吗?

向前声明对
类播放器:public Mob
没有帮助,因为编译器需要完整的继承定义


因此,你在Mob.h中最有可能的一个包含项是引入Player.h,这会将Player置于Mob之前,从而触发错误。

我已经解决了类似的问题,找到了解决方案,并将其作为经验法则

解决方案/经验法则

//File - Foo.h
#include "Child.h"
class Foo 
{
//Do nothing 
};

//File - Parent.h
#include "Child.h" // wrong
#include "Foo.h"   // wrong because this indirectly 
                   //contain "Child.h" (That is what is your condition)
class Parent 
{
//Do nothing 
Child ChildObj ;   //one piece of advice try avoiding the object of child in parent 
                   //and if you want to do then there are diff way to achieve it   
};

//File - Child.h
#include "Parent.h"
class Child::public Parent 
{
//Do nothing 
};
不要在父类中包含子类

如果您想知道在父类中拥有子对象的方法,请参考链接


谢谢

我知道这不是解决这个问题的最好办法,但至少对我来说是有效的。您可以将所有其他包含项放入cpp文件中:

#include "OmiGame/OmiGame.h"
#include "PlayState.h"
#include "Mob.h"
#include "resources.h"

这些文件在同一个目录中吗?你知道,如果你为所有私有成员提供访问器,它会以某种方式破坏封装…@Deduplicator它没有。只有四个私人成员有访问器,因为暴徒需要根据他们做出不同的反应,但他们需要共享这些成员,这样重用的代码也可以访问他们。@格雷格:所以他们是公共成员,即使代码试图欺骗你相信不是这样。@Deduplicator True,getter/setter编码风格有争议,但我是通过这种方式学习OO编程的,所以这已经成为一种习惯。这完全取决于个人喜好和习惯。删除
#包括“PlayState.h”
有效。PlayState声明玩家,但玩家也声明PlayState,因此不需要该行。谢谢