从派生类和基类调用函数

时间:2016-06-06 18:18:00

标签: c++ visual-c++

#include <iostream>  

class Base  
{  
public: 
    virtual ~Base() {}  
    virtual void f()  
    {  
        std::cout << "base\n";  
    }
};

class Derived : public Base
{  
public:  
    virtual ~Derived() {}  
    virtual void f()    
    {  
        std::cout << "derived\n";  
    }  
};  

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

所以我打电话给Derived::f,但我也打电话给Base::f。还有其他方法,而不是在Base::f()内调用Derived::f()吗?

1 个答案:

答案 0 :(得分:2)

听起来你想要的是Non Virtual Interface(NVI)设计。当你想要派生类的自定义点(例如多态),但是有点保证调用流时,这很好。

class Base  
{  
public:

    virtual ~Base() {}  

    void f()  
    {
        // ... do something that always run before
        f_impl();
        // ... and after the extension point
    }

protected:

    virtual void f_impl()
    {
    }
};

class Derived : public Base
{  
protected:  

    virtual void f_impl() override
    {
        std::cout << "extended!\n";
    }  
};

int main()  
{  
    Derived d;  
    d.f(); // Base can _always_ run things before and after Derived
}