私有和受保护的纯虚拟函数之间有什么区别吗

Is there any difference between a private and protected pure virtual function?

本文关键字:之间 什么 函数 区别 受保护 虚拟      更新时间:2023-10-16

我可以理解,可能有理由将已实现(而不是纯)的虚拟函数声明为私有或受保护。当然,如果您将一个已实现的虚拟方法声明为受保护的,那么您的子类可以调用基类的方法(其他人都不能)。如果您将其声明为私有,那么只有基类可以调用虚拟方法的默认实现。

然而,对于纯虚拟,没有基本实现。。。那么,将纯虚拟声明为私有或受保护在功能上是否等效?受保护的纯虚拟没有意义,因为您永远无法调用基类的相应方法。在任何情况下,受保护的纯虚拟都有意义吗?

SO上有一些类似的话题,但我找不到任何能简洁回答我问题的东西。

是否存在受保护的纯虚拟感觉

我认为你在这里指的是私人的(而不是受保护的),但我想我理解你的观点。事实上,纯虚拟的访问类型可以在派生类中重写。这里有一个例子可以帮助您了解私有和受保护的纯虚拟之间的区别:

class Parent
{
  protected: virtual void foo() = 0;
  private:   virtual void bar() = 0;
  public:            void test() { foo(); bar(); }
};
class Child : public Parent
{
  public: void test2() { foo(); /* bar(); // cannot be called here */ }
};
class GrandChild : public Child
{
  // access types here can be anything for this example
  public: void foo() { cout << "foo" << endl; }
  public: void bar() { cout << "bar" << endl; }
};

可以实现第一个纯虚拟函数!

#include <iostream>
class Animal
{
public:
  void eat(void);
protected:
  virtual void doEat(void)=0;
};
void Animal::eat(void)
{
  doEat();
}
void Animal::doEat(void)
{
  std::cout << "animal" << std::endl;
}
class Tiger : public Animal
{
private:
  virtual void doEat(void)
  {
    Animal::doEat();//here is the difference between protected and private
    std::cout << "tiger" << std::endl;
  }
};
int main(void)
{
  Animal *p = new Tiger();
  p->eat();
  return 0;
}

其次,Herb Sutter解释了何时使用"虚拟专用"或"虚拟保护",你可以阅读这篇文章。我认为这解释了为什么我们这样做——不仅仅是我们可以!文章说:"更喜欢将虚拟函数私有化,只有当派生类需要调用虚拟函数的基本实现,使虚拟函数受到保护时",你的问题是关于纯虚拟函数,我不太确定是否满足这一原则。