Can a nested C++ class inherit its enclosing class?

江枫思渺然 提交于 2019-11-27 23:05:09

问题


I’m trying to do the following:

class Animal
{
    class Bear : public Animal
    {
        // …
    };

    class Giraffe : public Animal
    {
        // …
    };
};

… but my compiler appears to choke on this. Is this legal C++, and if not, is there a better way to accomplish the same thing? Essentially, I want to create a cleaner class naming scheme. (I don’t want to derive Animal and the inner classes from a common base class)


回答1:


You can do what you want, but you have to delay the definition of the nested classes.

class Animal
{
   class Bear;
   class Giraffe;
};

class Animal::Bear : public Animal {};

class Animal::Giraffe : public Animal {};



回答2:


The class type is considered incomplete until the end of its definition is reached. You cannot inherit from incomplete class so you cannot inherit from enclosing class.

EDIT: Correction
As Richard Wolf corrected me: It is possible to inherit from enclosing class if you delay the definition of the nested classes. See his answer for details.




回答3:


Doesn't really answer the question, but I think you're misusing nested class, maybe you should have a look at namespaces (by the way, the answer is "it's not possible, because Animal is an incomplete type").




回答4:


I'm not clear what you are trying to achieve here but you may be able to get it via namespaces.

namespace creatures
{

class Animal
{
};

class Bear : public Animal
{
};

class Giraffe : public Animal
{
};


}

This declares Bear and Giraffe as types of animals but puts the whole thing in a namespace if you are looking for the base class to not pollute the global namespace.




回答5:


It's always worth considering the ATL method of "Upside-Down Inheritance". It makes my head hurt every time I need to do this, but the efficiency of the object-code you get is unbeatable. Somewhere I clipped the article by Jim Beveridge which was the best explanation I ever saw, but this is hard to find today, I just see a reference to it.

"Mar 25, 2004 ... An excellent article from Jim Beveridge: ATL and Upside-Down Inheritance.."



来源:https://stackoverflow.com/questions/1485985/can-a-nested-c-class-inherit-its-enclosing-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!