【问题标题】:Multi-level class inheritance with inconsistent constructors具有不一致构造函数的多级类继承
【发布时间】:2013-07-26 18:45:48
【问题描述】:

我有 3 个相互派生的类 - GameScreen 是 MenuScreen 派生自的基类。然后我有第三个类“TitleScreen”,它派生自“MenuScreen”。

流程基本上来自基类:'GameScreen' -> 'MenuScreen' -> 'TitleScreen'

基类“GameScreen”的构造函数中没有参数,就像“TitleScreen”一样,但是我需要“MenuScreen”的参数。我目前的头文件为:

GameScreen.h

class GameScreen
{
public:
    GameScreen();
}

MenuScreen.h

class MenuScreen : public GameScreen
{
public:
    MenuScreen(std::string title);
}

TitleScreen.h

class TitleScreen : public MenuScreen
{
public:
    TitleScreen(std::string title) : MenuScreen(title);
}

我很难理解的是这在 C++ 中是否可行(我正在关注执行此操作的游戏状态管理的 C# 示例)。通读一些书籍中的类继承,我只介绍了从基类继承的参数,因为我的示例基类没有参数。

【问题讨论】:

  • 是的,它和你写的完全一样——除了你应该在实际实现中调用 MenuScreen 构造函数,而不是在构造函数的声明中。

标签: c++ class inheritance constructor multi-level


【解决方案1】:
  1. 您在每个类声明后都缺少;

  2. 如果您写TitleScreen(std::string title) : MenuScreen(title),您正在定义方法的主体,但主体缺失...所以您应该只在您的 TitleScreen.h 中声明:

    class TitleScreen : public MenuScreen
    {
    public:
        TitleScreen(std::string title);
    };
    

    然后将构造函数的主体放到TitleScreen.cpp:

    #include "TitleScreen.h"
    
    TitleScreen::TitleScreen(std::string title) : MenuScreen(title)
    {
        // ..
    }
    

编辑:将术语一致修正为this question

【讨论】:

  • 您将声明与定义术语混淆了。还值得一提的是,两者可以像 C# 中那样一起使用,也可以像您的示例中那样单独使用,可能各有利弊。
  • 感谢您的澄清!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
  • 2012-01-31
  • 2015-06-20
相关资源
最近更新 更多