受保护的方法在c++中继承时可以成为私有方法吗?

A protected method can become a private method when inherited in c++?

我一直在研究继承,我试过这段代码:

#include <iostream> 
#include <string>

class Foo
{
public:
    virtual void func() = 0;

protected:
    virtual void doSum() const = 0;
};

class Bar : public Foo
{
public:
    void func() { 
        doSum();
    }

protected:
    void doSum() const
    {
        std::cout << "hi, i'm doing something" << std::endl;
    }
};

int main() 
{ 
    Foo* ptr = new Bar();
    ptr->func();

   return 0; 
}

所以我也尝试用 private 替换 class Bar 中的 protected 关键字,如下所示:

private:
    void doSum() const
    {
        std::cout << "hi, i'm doing something" << std::endl;
    }

并且代码恰好可以正常工作...

所以我的问题是,如果在实现派生 class 时将受保护方法声明为私有,是否有任何区别?如果有,它们是什么?我什至可以这样做吗?

So my question is, is there any difference if I declare a protected method private when implementing a derived class?

没有。没有区别。不幸的是,C++ 标准没有对派生 class 强加任何要求,以将重写虚函数置于任何特定的可访问范围内。这意味着,基础 class 可以声明一个受保护的虚拟方法,派生 class 可以在 public/protected/private 范围内实现该方法,代码仍然合法并且可以工作。

So my question is, is there any difference if I declare a protected method private when implementing a derived class?

是的。

If so, what are they?

这将阻止派生 class 的下一级调用派生 class 的实现。

class Foo
{
   protected:
      virtual void doSum() const = 0;
};

class Bar : public Foo
{
   private:
      void doSum() const
      {
         std::cout << "hi, i'm doing something" << std::endl;
      }
};

class Baz : public Bar
{
   public:
      void doSum() const
      {
         //===========================
         Bar::doSum(); // NOT ALLOWED
         //===========================
      }
};

Am I even allowed to do this?

是的。