为什么我不能在派生的 class 覆盖函数中调用受保护的虚拟基 class 函数?

Why can't I call protected virtual base class function in the derived class overridden function?

class Base
{
protected:
    virtual void show()
    {
        // Do some stuff.
    }
};

class Derived : public Base
{
protected:
    virtual void show()
    {
        // Do some stuff.
    }
};

class Derived_2 : public Derived
{
protected:
    virtual void show()
    {
        this->show();    // error: Base::show() is in accessible
        show();          // error: Base::show() is in accessible
        Derived::show(); // error: Base::show() is in accessible
    }
};

在上述情况下,调用虚拟基础 class 函数(在派生 classes 中被覆盖)会出错。

如果我理解你是对的并且你想打电话给 Base::show() 那么你可以通过以下方式做到这一点:

Derived::Base::show();Base::show();

但是如果你只是想调用 super class 的方法,你有一个正确的代码。

我能找到的唯一错误是,您从 itsel 调用 show 导致无限递归并以堆栈溢出错误结束。

但是这段代码编译 运行 甚至没有警告:

class Derived_2 : public Derived
{
public:
    virtual void show()
    {
        //this->show();    // infinite recursion => stack overflow
        Base::show();    // ok calls show() from Base
        Derived::show();    // ok calls show() from Derived
        std::cout << "Derived2" << std::endl;
    }
};

(我在测试中声明public直接调用它)