【问题标题】:Call function from derived and base class从派生类和基类调用函数
【发布时间】:2016-06-06 18:17:59
【问题描述】:
#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。除了在Derived::f() 中调用Base::f() 之外,还有其他方法吗?

【问题讨论】:

标签: c++ visual-c++


【解决方案1】:

听起来你想要的是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
}

【讨论】:

    猜你喜欢
    • 2011-06-19
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 2011-05-03
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多