首页 > 解决方案 > 如何确保调用覆盖的函数

问题描述

有什么方法可以确保从子类中的重写函数调用基类函数。

例子:

#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然后子类将覆盖受保护函数。但是您可以想象,如果将其应用于基类场景的基类的基类,并且必须调用其中的每个实现,这将变得非常混乱。是否有其他方法可以实现相同的目标?

标签: c++c++11inheritanceoverriding

解决方案


推荐阅读