简体   繁体   English

C++ 中的嵌套类、继承和共享指针

[英]Nested classes, inheritance and shared pointers in C++

The program below fails, obviously, in the return expression:很明显,下面的程序在返回表达式中失败了:

#include <memory>

class Base {
    public:

        class Nested {
            public:
                int c;
        };
};

class A : public Base {
    public:

        class Nested : public Base::Nested {
            public:
                int c = 1;
        };
};

class B : public Base {
    public:

        class Nested : public Base::Nested {
            public:
                int c = 2;
        };
};

int main() {
    std::shared_ptr<Base> X = std::make_shared<A>();

    return X::Nested.c;
};

How can I get Nested.c value of X?如何获得 X 的Nested.c值?

In other words, I have one base class ( Base ) and two derived classes ( A and B ).换句话说,我有一个基类( Base )和两个派生类( AB )。 Each derived class has a nested class ( Nested ).每个派生类都有一个嵌套类( Nested )。 I want to called Nested.c from an instance X , which is dynamically selected as one of the derived classes.我想从实例X调用Nested.c ,该实例被动态选择为派生类之一。

Probably just a misconception about nested classes.可能只是对嵌套类的误解。 A Nested class does not magically add members to it's parent class.嵌套类不会奇迹般地将成员添加到它的父类。 You need to do that manually, for example:您需要手动执行此操作,例如:

class Base {
  public:

    class Nested {
        public:
            int c;
    };

    Nested nested; // member of nested class Base::Nested.
};

Keep in mind that Base::Nested , A::Nested and B::Nested are all different classes.请记住Base::NestedA::NestedB::Nested都是不同的类。 Allthough they look similiar they are not related at all.尽管它们看起来很相似,但它们根本没有关系。


Maybe the following is what you want: 也许以下是您想要的:

 #include <memory> class Base { private: class Nested { public: int c; }; Nested nested; // member of nested class Base::Nested. public: virtual int getC() const { return this->nested.c; } }; class A : public Base { private: class Nested { public: int c = 1; }; Nested nested; // member of nested class A::Nested. public: int getC() const override { return this->nested.c; } }; class B : public Base { private: class Nested { public: int c = 2; }; Nested nested; // member of nested class B::Nested. public: int getC() const override { return this->nested.c; } }; int main() { std::shared_ptr<Base> X = std::make_shared<B>(); return (*X).getC(); };

Each class has it's own member of it's own nested class and returns c with a virtual getter.每个类都有它自己的嵌套类的成员,并返回带有虚拟 getter 的c

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

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