错误C2504:基类未定义

Gre*_*ven 8 c++ inheritance header class

我之前多次遇到过这个错误并最终找到了解决方案,但是这个让我难过.我有一个由'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(); }
};
Run Code Online (Sandbox Code Playgroud)

这是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);
};
Run Code Online (Sandbox Code Playgroud)

并且,正如您可能猜到的,这是错误:

error C2504: 'Mob' : base class undefined   player.h
Run Code Online (Sandbox Code Playgroud)

我有前锋宣布的暴徒,我希望修复任何循环依赖.请有人帮帮我吗?

The*_*ish 24

前向声明无济于事,class Player : public Mob因为编译器需要完整的继承定义.

所以很可能你在Mob.h中的一个包含引入了Player.h,然后将Player放在Mob之前,从而触发错误.

  • 删除`#include"PlayState.h"`工作.PlayState声明了Player,但Player也声明了PlayState,因此不需要该行.谢谢. (2认同)

小智 9

我已经解决了类似的问题,我解决了问题,并为我做了一个拇指规则

解决方案/拇指规则

//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 
};
Run Code Online (Sandbox Code Playgroud)

不要将孩子包括在父类中.

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

谢谢