问题描述
示例:
#include <iostream>
class Base
{
public:
virtual void func()
{
std::cout << "Really important code was ran" << std::endl;
}
};
class ChildExplicit : public Base
{
void func() override
{
Base::func();
std::cout << "child class explicitly calling Base::func" << std::endl;
}
};
class ChildImplicit : public Base
{
void func() override
{
std::cout << "child not explicitly calling Base::func" << std::endl;
}
};
int main()
{
Base* explicitChild = new ChildExplicit();
Base* implicitChild = new ChildImplicit();
explicitChild->func();
std::cout << std::endl;
implicitChild->func();
}
这应该输出:
Really important code was ran
child class explicitly calling Base::func
Really important code was ran
child not explicitly calling Base::func
或产生某种错误,即 Base::func
未在 ChildImplicit::func
中调用。
一种可能的解决方案是使 func
非虚拟并创建将在 Base::func
中调用的第二个受保护的函数,然后子类将覆盖受保护的函数。但是您可以想象,如果将其应用于 Base 类场景的 Base 类的 Base 类,并且必须调用每个实现,这会变得非常混乱。是否有其他方法可以实现相同的目标?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)