问题描述
为什么总是基类在多态中具有纯虚函数?当您知道它是以任何方式专门用于派生类时,需要在基类中提供虚函数的实现吗?
分享只有在知情的情况下才有利可图。
基类实现的一个原因是 如果虚拟函数不是专门用于派生类,则提供默认行为。 如果一个类是专门设计为始终作为基类而永远不会单独实例化
,那么拥有一个纯虚函数将成为该设计的一部分。 但是,为其他人使用而生成的库可能包含可以按原样实例化或作为基类的类。 在这种情况下,虚拟函数的基类实现
是必不可少的。
Why cant always base class have pure virtual function in polymorphism? what is the need to provide implementation of a virtual function in base class when you know that it is any way going to be specialized in derived classes?
Sharing is profitable only if it happens with knowledge.
One reason to for a base class implementation is to provide default behavior if the virtual function is not specialized in a derived class. If a class is is specifically designed to always serve as a base class and never to be instantiated alone, then having a pure virtual function would be part of that design. However, a library that is produced for consumption by others may contain classes that can be instantiated as-is or serve as base classes. In that case a base class implementation for virtual functions is essential.
这篇关于为什么总是基类在多态中都有纯虚函数?当您知道它是以任何方式专门用于派生类时,需要在基类中提供虚函数的实现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!