我有一些这样的事件
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/