我知道这个主题有很多问题。但是,我无法理解使用抽象类而不是虚拟类的确切需求。如果我没有记错的话,抽象类也是隐式的虚拟类,它们之间的唯一区别是抽象方法必须在子类中被覆盖。那么,为什么虚拟课堂还不够?在什么情况下,我们确切需要抽象类而不是虚拟类?
首先,没有所谓的“虚拟阶级”。我假设您要说的是一个多态类(至少具有一个虚拟成员函数,当然还有一个虚拟析构函数)。
抽象类(那些至少具有一个纯虚拟成员函数的类)没有“需要”,但它们有助于创建无法实例化的接口,而只能提供一堆可重写的成员函数。如果实例化这样一个通用基类毫无用处或违背了设计师的意图,那么它允许您提供一个通用基类来辅助多态性。
/**
* Instantiating `IType` cannot serve a purpose; it has
* no implementation (although I _can_ provide one for `foo`).
*
* Therefore, it is "abstract" to enforce this.
*/
struct IType
{
virtual void foo() = 0;
virtual ~IType() {}
};
/**
* A useful type conforming to the `IType` interface, so that
* I may store it behind an `IType*` and gain polymorphism with
* `TypeB`.
*/
struct TypeA : IType
{
virtual void foo() override {}
};
/**
* A useful type conforming to the `IType` interface, so that
* I may store it behind an `IType*` and gain polymorphism with
* `TypeA`.
*/
struct TypeB : IType
{
virtual void foo() override {}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句