c++ - 强制调用基类虚函数

标签 c++ class function inheritance virtual

我有一些这样的事件

class Granpa // this would not be changed, as its in a dll and not written by me
{
public:

   virtual void onLoad(){}

}

class Father :public Granpa // my modification on Granpa
{
public:

    virtual void onLoad()
    {
       // do important stuff
    }

}

class Child :public Father// client will derive Father
{

   virtual void onLoad()
   {
       // Father::onLoad(); // i'm trying do this without client explicitly writing the call

       // clients code
   }
}

有没有办法在不实际编写 Father::onLoad() 的情况下强制调用 onLoad?

欢迎使用黑客解决方案 :)

最佳答案

如果我理解正确的话,您希望这样每当调用被覆盖的函数时,必须始终首先调用基类实现。在这种情况下,您可以调查 template pattern .比如:

class Base
{
public:
    void foo() {
        baseStuff();
        derivedStuff();
    }

protected:
    virtual void derivedStuff() = 0;
private:
    void baseStuff() { ... }
};

class Derived : public Base {
protected:
    virtual void derivedStuff() {
        // This will always get called after baseStuff()
        ...
    }
};

关于c++ - 强制调用基类虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9724371/

相关文章:

python - 如何从另一个模块更改类对象参数(python)

class - 调用一个类后,括号有什么作用?

java - 使用当前类中的变量运行不同类中的方法

PHP mail()发送2份

c - C语言扑克软件原型(prototype),找出顺子功能的问题

c++ - 有没有办法在 2 列中显示我的素数列表输出?

c++ - 在C语言中使用遗传算法求一个数的平方根时如何实现选择和交叉

C++ vector 引用

c++ - C++ 标准的哪一部分阻止显式指定此模板的参数?

javascript - AngularJS运行执行功能?