【问题标题】:How to properly inherit base class in c++ and override virtual function如何在C++中正确继承基类并覆盖虚函数
【发布时间】: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


【解决方案1】:

正如 Retired Ninja 所说,代码中有一个循环包含问题。 GameObj.h 包含 Game.h,Game.h 包含 Player.h。为了解决这个问题,我删除了 GameObj.h 中包含的 Game.h。

GameObj.h

#pragma once
#include <SDL.h>

class GameObj
{
public:
  GameObj(const char* path);

  virtual ~GameObj() = default;

  virtual void update() = 0;

  void render();

protected:
  SDL_Texture* tex{ nullptr };
  SDL_Rect srcR;
  SDL_Rect dstR;
};

GameObj.cpp

#include "GameObj.h"
#include "TextureManager.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);
}

【讨论】:

  • 很高兴听到它有效。您还应该考虑@WBUCK 关于虚拟析构函数的评论。它应该可以为您省去一些麻烦。
  • 看起来问题出在 game.h 中包含 player.h 中包含 game.h,但我想如果它有效的话,你已经解决了。
猜你喜欢
  • 1970-01-01
  • 2012-02-05
  • 2014-01-15
  • 2014-02-06
  • 2013-01-26
  • 1970-01-01
  • 2023-03-17
  • 2011-01-10
  • 1970-01-01
相关资源
最近更新 更多