简体   繁体   English

C ++-在父类中定义子类

[英]C++ - Defining child class within parent class

While working on a personal project, I have found myself in a situation where I want to create reusable chunks of code for child classes of my abstract parent class that can implement some of it's pure virtual methods. 在进行个人项目时,我发现自己想为抽象父类的子类创建可重用的代码块,以实现某些纯虚拟方法。 For that purpose I have created a an intermediate parent class inheriting after the primary child class. 为此,我创建了一个中间父类,该中间父类在主要子类之后继承。 However, due to the nature of the final child classes within the project it doesn't make sense for the intermediate parent class to be accessible to any object other than the child classes. 但是,由于项目中最终子类的性质,中间子类对子类以外的任何对象都没有意义。 As a result I have created this type of class structure: 结果,我创建了这种类型的类结构:

class Foo
{
protected:
    class Bar : protected Foo
    {
    public:
        void a()
        {
            //implementation of a()
        }
    };

public:
    virtual void a() = 0;
    virtual void b() = 0;
};

class Beep : public Foo, private Foo::Bar
{
    void b()
    {
        //implementation of b()
    }
};

(I am aware of the diamond inheritance problem and other issues caused by inheriting from an ancestor class via multiple sources. For the purpose of this question, please assume it to be a non-issue as it is not the focus.) (我知道钻石继承问题以及通过多个来源从祖先类继承而导致的其他问题。出于这个问题的目的,请假定它不是问题,因为它不是焦点。)

The above code results in the 'incomplete type not allowed' error upon attempting to define Foo as the parent of Bar . 上面的代码在尝试将Foo定义为Bar的父级时导致“不允许不完整的类型”错误。 Is there a way to restructure the code to remove the error while maintaining the desired class/accessibility structure? 有没有一种方法可以在保持所需的类/可访问性结构的同时重组代码以消除错误?

While I am interested in how one would achieve what I described (by this point mostly due to curiosity), I will accept alternative solutions as long as they result in a matching behavior, that is: code implementing parts of an abstract base class only visible/accessible to objects inheriting after said base class. 尽管我对如何实现我所描述的内容感兴趣(此时,主要是出于好奇心),但我会接受替代解决方案,只要它们导致匹配的行为即可,即:实现抽象基类部分的代码仅可见/可以访问在所述基类之后继承的对象。

You can forward declare Bar and define it after Foo . 您可以转发声明Bar并在Foo之后定义它。

class Foo
{
protected:
    class Bar;

public:
    virtual void a() = 0;
    virtual void b() = 0;
};

class Foo::Bar : protected Foo
{
public:
    void a()
    {
        //implementation of a()
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM