为什么我们需要抽象类而不是虚拟类?

kat*_*nai 3 c++ oop

我知道关于这个话题有很多问题.但是,我无法理解使用抽象类而不是虚拟类的确切需要.如果我没有弄错,抽象类也隐式地是一个虚拟类,它们之间的唯一区别是必须在子类中重写抽象方法.那么,为什么虚拟课不足够?在哪些情况下我们确实需要抽象类而不是虚拟类?

Lig*_*ica 6

首先,没有"虚拟课"这样的东西.我假设您打算说一个多态类(至少有一个虚拟成员函数,当然还有一个虚拟析构函数).

抽象类(具有至少一个纯虚拟成员函数的类)没有"需要",但它们有助于创建无法实例化的接口,但仅提供一堆可重写的成员函数.它允许您提供一个公共基类来帮助实现多态,在这种情况下,实例化这样一个共同的基类将没有任何意义,或者会违背设计者的意图.

/**
 * 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 {}
};
Run Code Online (Sandbox Code Playgroud)