覆盖嵌套 class 的虚函数

Overriding a virtual function of a nested class

假设我有以下 class:

class Base {
public:
    class Nested {
        virtual void display() {
            std::cout << "Not overridden" << std::endl;
        }
    };
    Nested N;
};

我还有一个名为 Derived 的 class 继承自 class Base.

是否可以重写在 Nested 中声明的 display() 方法,以便在 Derived class 中这样做:

void display() {
    std::cout << "Overridden" << std::endl;
}

如果是,怎么做?

如果没有,我还有什么其他选择?

嵌套class(来自cppreference):

The name of the nested class exists in the scope of the enclosing class, and name lookup from a member function of a nested class visits the scope of the enclosing class after examining the scope of the nested class. Like any member of its enclosing class, the nested class has access to all names (private, protected, etc) to which the enclosing class has access, but it is otherwise independent and has no special access to the this pointer of the enclosing class.

并且从 c++11 开始

Declarations in a nested class can use any members of the enclosing class, following the usual usage rules for the non-static members.

这么马虎的说,嵌套classes是关于名称和访问成员的。就是这样。

Base 派生的 class 不继承方法 display,因为 Base 没有方法 display。关于从 Base 继承,与以下几乎没有区别:

class Nested {
    virtual void display() {
        std::cout << "Not overridden" << std::endl;
    }
};

class Base {
public:
   Nested N;
};

class Derived : public Base {};

Derived 继承成员 N,但没有方法,因为 Base 没有方法(除了特殊编译器生成的方法)。