简单单继承关系图
注意该图中从常规到特定的进度。在大多数类层次结构的设计中发现的另一个常见特性是,派生类与基类具有“某种”关系。在该图中,Book 是一种 PrintedDocument,而 PaperbackBook 是一种 book。
该图中的另一个要注意的是:Book 既是派生类(来自 PrintedDocument),又是基类(PaperbackBook 派生自 Book)。此类类层次结构的框架声明如下面的示例所示:
// deriv_SingleInheritance.cpp
// compile with: /LD
class PrintedDocument {};
// Book is derived from PrintedDocument.
class Book : public PrintedDocument {};
// PaperbackBook is derived from Book.
class PaperbackBook : public Book {};
PrintedDocument 被视为 Book 的“直接基”类;它是 PaperbackBook 的“间接基”类。差异在于,直接基类出现在类声明的基础列表中,而间接基类不是这样的。
在声明派生的类之前声明从中派生每个类的基类。为基类提供前向引用声明是不够的;它必须是一个完整声明。
在前面的示例中,使用访问说明符 public。 成员访问控制中介绍了公共的、受保护的和私有的继承的含义。
类可用作多个特定类的基类,如下图所示。
注意
有向非循环图对于单继承不是唯一的。它们还用于表示多重继承关系图。 多重继承中对本主题进行了说明。
在继承中,派生类包含基类的成员以及您添加的所有新成员。因此,派生类可以引用基类的成员(除非在派生类中重新定义这些成员)。当在派生类中重新定义了直接或间接基类的成员时,范围解析运算符 (::) 可用于引用这些成员。请看以下示例:
// deriv_SingleInheritance2.cpp
// compile with: /EHsc /c
#include <iostream>
using namespace std;
class Document {
public:
char *Name; // Document name.
void PrintNameOf(); // Print name.
};
// Implementation of PrintNameOf function from class Document.
void Document::PrintNameOf() {
cout << Name << endl;
}
class Book : public Document {
public:
Book( char *name, long pagecount );
private:
long PageCount;
};
// Constructor from class Book.
Book::Book( char *name, long pagecount ) {
Name = new char[ strlen( name ) + 1 ];
strcpy_s( Name, strlen(Name), name );
PageCount = pagecount;
};












