简体   繁体   English

覆盖嵌套 class 的虚拟 function

[英]Overriding a virtual function of a nested class

Let's say I have the following class:假设我有以下 class:

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

And I have another class named Derived that inherits from the class Base .我还有另一个名为Derived的 class 继承自 class Base

Is it possible to override the display() method declared inside the Nested so that in the Derived class it does this instead:是否可以覆盖Nested中声明的display()方法,以便在Derived的 class 中这样做:

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

If so, how?如果是这样,怎么做?

If not, what other options do I have?如果没有,我还有什么其他选择?

Nested class (from cppreference ):嵌套 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. 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. 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.

and since c++11自 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.嵌套 class 中的声明可以使用封闭 class 的任何成员,遵循非静态成员的通常使用规则。

So sloppy speaking, nesting classes is about names and accessing members.这么草率地说,嵌套类是关于名称和访问成员的。 Thats it.而已。

A class deriving from Base does not inherit a method display , because Base has no method display .Base派生的 class 不继承方法display ,因为Base没有方法display Concerning inheriting from Base there is little difference to:关于从Base继承几乎没有什么区别:

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

class Base {
public:
   Nested N;
};

class Derived : public Base {};

Derived inherits the member N , but no methods, because Base has no methods (apart from the special compiler generated ones). Derived继承成员N ,但没有方法,因为Base没有方法(除了特殊的编译器生成的方法)。

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

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