私有和受保护的纯虚拟函数之间有什么区别吗
Is there any difference between a private and protected pure virtual function?
我可以理解,可能有理由将已实现(而不是纯)的虚拟函数声明为私有或受保护。当然,如果您将一个已实现的虚拟方法声明为受保护的,那么您的子类可以调用基类的方法(其他人都不能)。如果您将其声明为私有,那么只有基类可以调用虚拟方法的默认实现。
然而,对于纯虚拟,没有基本实现。。。那么,将纯虚拟声明为私有或受保护在功能上是否等效?受保护的纯虚拟没有意义,因为您永远无法调用基类的相应方法。在任何情况下,受保护的纯虚拟都有意义吗?
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解释了何时使用"虚拟专用"或"虚拟保护",你可以阅读这篇文章。我认为这解释了为什么我们这样做——不仅仅是我们可以!文章说:"更喜欢将虚拟函数私有化,只有当派生类需要调用虚拟函数的基本实现,使虚拟函数受到保护时",你的问题是关于纯虚拟函数,我不太确定是否满足这一原则。
相关文章:
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 这 4 个 lambda 表达式之间有什么区别?
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 不同的类或结构初始化方法之间的性能差异是什么?
- "constinit"和"constexpr"之间的真正区别是什么?
- 在什么条件下使用 std::memcpy 在对象之间复制是安全的?
- 移动语义和深层/浅层复制之间有什么关系?
- 这两种C++语法之间有什么区别?
- #include < conio.h> 和 getch() 方法之间的关系是什么?
- ((int) a) 和 (int(a)) 之间的区别是什么?
- ( var > x) 和 ( x < var)之间有什么区别吗?
- 在 C 和 C++ 中作为函数参数,int **a 和 int a[][] 之间有什么确切的区别
- 返回引用实例和非引用实例(return mystr & vs mystr)之间的区别是什么?
- 超市管理系统的类别之间应该是什么关系?
- 指针和程序性能之间有什么关系吗?
- 这些初始化之间有什么区别?
- 空字符和"\0"之间有什么区别?
- 无符号长整型和无符号 int 之间有什么区别,这 2 种类型应该如何在 c# 中封送?