Pri*_*tic 18 c++ inheritance pure-virtual
我可以理解,可能有理由声明一个已实现(而不是纯粹)的私有或受保护的虚拟函数.Afaik,如果您将已实现的虚拟方法声明为受保护,则您的子类可以调用基类的方法(并且没有其他人可以).如果将其声明为private,则只有基类可以调用virtual方法的默认实现.
但是,对于纯虚拟机,没有基本实现......那么在功能上是否等同于将纯虚拟声明为私有或受保护?受保护的纯虚拟没有意义,因为您无法调用基类的相应方法.是否存在受保护的纯虚拟有意义的情况?
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; }
};
Run Code Online (Sandbox Code Playgroud)
第一个纯虚函数可以实现了!
#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;
}
Run Code Online (Sandbox Code Playgroud)
其次,Herb Sutter解释了何时使用“虚拟私有”或“虚拟保护”,你可以阅读这篇文章。我认为这解释了为什么我们不仅可以这样做!文章说:“宁愿让虚拟函数私有,只有当派生类需要调用虚函数的基实现时,才使虚函数受到保护”,你的问题是关于纯虚函数的,我不太确定是否满足这个原则。