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

Nested classes, inheritance and shared pointers in C++

下面的程序显然在 return 表达式中失败了:

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

如何获得 X 的 Nested.c 值?

换句话说,我有一个基数class (Base) 和两个派生的classes (AB)。每个派生的 class 都有一个嵌套的 class (Nested)。我想从实例 X 调用 Nested.c,它被动态选择为派生的 classes 之一。

可能只是对嵌套 classes 的误解。嵌套 class 而不是 神奇地将成员添加到其父 class。您需要手动执行此操作,例如:

class Base {
  public:

    class Nested {
        public:
            int c;
    };

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

请记住,Base::NestedA::NestedB::Nested 都是不同的 class。尽管它们看起来很相似,但它们根本没有关系。


也许以下就是你想要的:

#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();
};

每个 class 都有自己的嵌套成员 class 和 returns c 以及虚拟 getter。