本文介绍了强制调用基类虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些这样的事件
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
}
}
有没有办法强制调用onLoad而不实际写 Father :: onLoad()?
Is there a way to force calling onLoad without actually writing Father::onLoad()?
欢迎使用Hackish解决方案:)
Hackish solutions are welcome :)
推荐答案
如果我理解正确,被调用,基类实现必须总是先调用。在这种情况下,您可以调查。类似的东西:
If I understand correctly, you want it so that whenever the overriden function gets called, the base-class implementation must always get called first. In which case, you could investigate the template pattern. Something like:
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()
...
}
};
这篇关于强制调用基类虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!