Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

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

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 {};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...