简体   繁体   English

覆盖虚函数的C ++ baseClass ::方法

[英]C++ baseClass::method in overriding a virtual function

If I have the following override of a virtual event: 如果我有以下覆盖的虚拟事件:

void derivedClass::method(event)
{

   // my stuff

   baseClass::method(event); // <--

}

what does the // <--- line does? // <---行是做什么的? What does it call? 它叫什么? I don't think it calls the base class' method because it's virtual (so no body) 我不认为它调用基类的方法,因为它是虚拟的(所以没有主体)

As you are suggesting, it calls the base class' method. 正如你的建议,它调用基类的方法。 The fact that it is virtual it only means it can be overridden and still access to the derived class' method from a pointer/reference to the base class. 它是虚拟的这一事实只意味着它可以被覆盖,并且仍然可以从指向基类的指针/引用访问派生类的方法。

The reason to do that can be easily seen with an example: 通过一个例子可以很容易地看出这样做的原因:

class Base {
public:
    virtual void foo() {
        /* do some generic stuff */
    }
};

class Derived : public Base {
public:
    void foo() {
        /* do some specific stuff */

        /* if you also want to do the generic stuff,
           you can call the same method from the base class. */
        Base::foo();
    }
}

It might be the case that you do not want to do the generic stuff for Derived class. 可能是您不想为Derived类执行泛型的东西。 Then you would just remove the call to Base::foo() . 然后你只需删除对Base::foo()的调用。

Here you have a good reference on virtual methods . 在这里,您可以很好地参考虚拟方法

It does call the base class method. 它确实调用了基类方法。 Yes, the derived method is being called "polymorphically", but it can call its base method using Base::method 是的,派生方法被称为“多态”,但它可以使用Base::method调用其基本Base::method

When qualified name ( <class name>::<method name> ) is used in a class method call, the method is called directly, non-virtually . 在类方法调用中使用限定名称( <class name>::<method name> )时,将直接调用该方法, 非虚拟方法 In your example, baseClass::method is called. 在您的示例中,将调用baseClass::method Since qualified name is used, the fact that the method is virtual means absolutely nothing and makes no difference whatsoever. 由于使用了限定名称,因此该方法是虚拟的这一事实绝对没有任何意义,并且没有任何区别。

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

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