【发布时间】:2021-10-22 20:25:28
【问题描述】:
我对 c++ 很陌生,我开始研究 SDL2 库来制作一个简单的平台游戏。我遇到了类继承的问题。我有一个父类(GameObj)和一个子类(Player)。当我尝试从 Player 继承 GameObj 时,编译器告诉我基类未定义。我正在尝试覆盖 Player 类中的更新函数,但是由于我收到“未定义基类”错误,它还告诉我覆盖函数没有覆盖任何内容。
GameObj.h
#pragma once
#include "Game.h"
class GameObj
{
public:
GameObj(const char* path);
~GameObj();
virtual void update() = 0;
void render();
protected:
SDL_Texture* tex{ nullptr };
SDL_Rect srcR;
SDL_Rect dstR;
};
GameObj.cpp
#include "GameObj.h"
GameObj::GameObj(const char* path)
{
tex = TextureManager::LoadImage(path);
srcR.x = srcR.y = 0;
srcR.w = srcR.h = 32 * 2;
dstR.x = dstR.y = 0;
dstR.w = dstR.h = srcR.w;
}
GameObj::~GameObj() {}
void GameObj::render() {
TextureManager::DrawTexture(tex, srcR, dstR);
}
Player.h
#pragma once
#include "Game.h"
#include "GameObj.h"
class Player : public GameObj
{
public:
Player(const char* path, int x, int y);
~Player();
void update() override;
private:
int x{ 0 };
int y{ 0 };
int speed{ 0 };
int velocity{ 0 };
};
Player.cpp
#include "Player.h"
Player::Player(const char* path, int x, int y) : GameObj(path){};
Player::~Player() {};
void Player::update ()
{
x++;
dstR.x = x;
dstR.y = y;
}
【问题讨论】:
-
由于您包含 GameObj.h,因此您无需在 Player.h 中转发声明
GameObj。编译问题中显示的代码时遇到的确切复制/粘贴错误是什么? -
你的文件
Game.h包括什么? -
啊,旧通函包括。
-
大声笑非常感谢!
-
这并不能解决您的问题,但万一没有人提到它,请确保您将
GameObj的析构函数virtual。即:virtual ~GameObj( ) = default
标签: c++ inheritance