类协议实现

可以实现类来强制执行协议。 这些类称为“抽象类”,因为无法创建该类类型的对象。 它们仅为派生而存在。

如果类包含纯虚函数或继承纯虚函数且不为它们提供实现,这样的类便为抽象类。 纯虚函数是使用 pure-specifier (= 0) 声明的虚函数,如下所示:

virtual char *Identify() = 0;

基类 Document 可能对所有派生类实施以下协议:

  • 必须实现一个适当的 Identify 函数。

  • 必须实现一个适当的 WhereIs 函数。

通过在设计 Document 类时指定此类协议,可确保类设计器在没有 Identify 和 WhereIs 函数的情况下将无法实现任何非抽象类。 因此,Document 类包含这些声明:

// deriv_ClassProtocolImplementation.cpp
// compile with: /LD
class Document {
public:
    //  Requirements for derived classes: They must implement
    //   these functions.
    virtual char *Identify() = 0;
    virtual char *WhereIs() = 0;
};

请参见

参考

派生类概述