gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:17:56 26 4
gpt4 key购买 nike

我有一些这样的事件

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com