基类的虚函数调用 [英] virtual function call from base class

查看:361
本文介绍了基类的虚函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我们有:


Class Base
{   
    virtual void f(){g();};
    virtual void g(){//Do some Base related code;}
};

Class Derived : public Base
{   
    virtual void f(){Base::f();};
    virtual void g(){//Do some Derived related code};
};

int main()
{
    Base *pBase = new Derived;
    pBase->f();
    return 0;  
}

其中 g code>将从 Base :: f()调用? Base :: g() Derived :: g()

谢谢...

推荐答案

派生类的g将被调用。如果你想调用基类中的函数,调用

The g of the derived class will be called. If you want to call the function in the base, call

Base::g();

。如果你想调用派生,但仍然希望有基本版本被调用,安排派生版本的g在其第一个语句中调用基本版本:

instead. If you want to call the derived, but still want to have the base version be called, arrange that the derived version of g calls the base version in its first statement:

virtual void g() {
    Base::g();
    // some work related to derived
}

从基础可以调用一个虚方法和控制转移到派生类中,用于模板方法设计模式。对于C ++,它更好地称为非虚拟接口。它也广泛应用于C ++标准库(C ++流缓冲区例如具有调用执行真正工作的虚函数的函数 pub ... ,例如 pubseekoff 调用受保护的 seekoff )。我在这个答案中写了一个例子:如何验证对象的内部状态?

The fact that a function from the base can call a virtual method and control is transferred into the derived class is used in the template method design pattern. For C++, it's better known as Non-Virtual-Interface. It's widely used also in the C++ standard library (C++ stream buffers for example have functions pub... that call virtual functions that do the real work. For example pubseekoff calls the protected seekoff). I wrote an example of that in this answer: How do you validate an object’s internal state?

这篇关于基类的虚函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆