c++ - 我怎样才能覆盖纯虚方法,但仍然强制子类实现相同的方法?

标签 c++

我有一个带有一个纯虚方法的抽象基类:

class Base
{
public:
    virtual void update() = 0;
};

有什么方法可以创建一个继承自 Base 的类,覆盖 update 方法,但仍然强制其子级实现 update方法?像这样:

class Base2 : public Base
{
public:
    void update() override
    {
        if(bSomeCondition)
        {
            update(); //Calls child's update method
        }
    }
    virtual void update() = 0; // Obviously not like this
};

我知道我可以在 Base2 中创建两个名称略有不同的新纯虚拟方法,并在子类中覆盖它们,但如果可能的话,我真的很想保留这些方法名称.

我猜这不可能吧?

最佳答案

可以提供纯虚函数的定义,而不是内联。

class Base2 : public Base
{
public:
    void update() override = 0;
};

void Base2::update() // Base2 is abstract regardless of this
{
    if(bSomeCondition)
    {
        update(); 
    }
}

但是,这对于当前的 Base2::update 实现没有用。因为子类无论如何都必须覆盖它,除非明确使用,否则不会调用 Base2 版本:

class Child: public Base2
{
public:
    void update() override
    {
        Base2::update(); //infinite recursion with such implementation
    }
};

// the other way would be to require calling it explicitly at call site

std::unique_ptr<Base2> ptr = std::make_unique<Child>();
ptr->Base2::update(); 

你应该做的是提供一个实现和另一个要调用的纯虚函数(可能是 protected):

class Base2 : public Base
{
public:
    void update() override;

protected:
    virtual void doStuff() = 0;
};

void Base2::update()
{
    if(bSomeCondition)
    {
        doStuff(); //Calls child's update method
    }
}

关于c++ - 我怎样才能覆盖纯虚方法,但仍然强制子类实现相同的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68208689/

相关文章:

c++ - "?"帮助按钮触发 WM_HELP _and_ WM_LBUTTONUP

c++ - 对未知大小数组的引用的列表初始化 : is it supposed to deduce the array size?

c++ - 将英特尔的 MKL(BLAS 和 LAPACK)链接到 GCC

c++ - 使用 C++ 代码获取 Windows Phone 8.1 中的唯一 DeviceId

c++ - 二值图像,使用 OpenCV 的白点浓度

c++ - 为瘦客户端设计客户端(胖)/服务器 + 额外的 REST API

c++ - 如何使用模板选择类(class)成员

c++ - 错误 C2679 : binary '=' : no operator defined which takes a right-hand operand of type

java - opencv - 匹配模板

c++ - ld : 4 duplicate symbols for architecture x86_64