跳至内容

Abstract Classes

抽象类与纯虚函数

抽象类用于创建通用实体,这些实体可用于创建更具体的派生类。抽象类只能作为其他类的基类使用,因此无法创建抽象类类型的对象。

包含至少一个纯虚函数的类即为抽象类。因此,从抽象类派生的类必须实现其所有纯虚函数,否则它们也将是抽象类。

通过使用“pure”修饰符语法,虚函数被声明为“纯虚函数”。以CAnimal类为例,该类的创建只是为了提供通用功能——CAnimal类型的对象过于通用,无法实际使用。因此,CAnimal是一个很好的抽象类示例:

class CAnimal
  {
public:
                      CAnimal();     // Constructor
   virtual void       Sound() = 0;   // A pure virtual function
private:
   double             m_legs_count;  // The number of the animal's legs
  };

这里的Sound()是一个纯虚函数,因为它使用了纯虚函数的修饰符PURE (=0)进行声明。

只有设置了PURE修饰符的虚函数才是纯虚函数: (=NULL) 或 (=0)。抽象类声明和使用的示例:

class CAnimal
  {
public:
   virtual void       Sound()=NULL;   // PURE method, should be overridden in the derived class, CAnimal is now abstract and cannot be created
  };
//--- Derived from an abstract class
class CCat : public CAnimal
 {
public:
  virtual void        Sound() { Print("Myau"); } // PURE is overridden, CCat is not abstract and can be created
 };

//--- Examples of wrong use
new CAnimal;         // Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract class" error
CAnimal some_animal; // Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract class" error

//--- Examples of proper use
new CCat;  // No error - the CCat class is not abstract
CCat cat;  // No error - the CCat class is not abstract

抽象类的限制

如果抽象类的构造函数调用了纯虚函数(直接或间接),结果将是未定义的。

//+------------------------------------------------------------------+
//| An abstract base class                                           |
//+------------------------------------------------------------------+
class CAnimal
  {
public:
   //--- A pure virtual function
   virtual void      Sound(void)=NULL;
   //--- Function
   void              CallSound(void) { Sound(); }
   //--- Constructor
   CAnimal()
    {
     //--- An explicit call of the virtual method
     Sound();
     //--- An implicit call (using a third function)
     CallSound();
     //--- A constructor and/or destructor always calls its own functions,
     //--- even if they are virtual and overridden by a called function in a derived class
     //--- If the called function is pure virtual,
     //--- its call will cause a critical runtime error: "pure virtual function call"
    }
  };

然而,抽象类的构造函数和析构函数可以调用其他成员函数。

最后更新于