在《C++箴言:确保公开继承模拟“is-a”》一文中论述了 C++ 将 public inheritance(公有继承)视为一个 is-a 关系。当给定一个 hierarchy(继承体系),其中有一个 class Student 从一个 class Person 公有继承,当为一个函数调用的成功而有必要时,需要将 Students 隐式转型为 Persons,它通过向编译器展示来做到这一点。用 private inheritance(私有继承)代替 public inheritance(公有继承)把这个例子的一部分重做一下是值得的: Gehl/i-
&e)p6Egl
class Person { ... }; ,TtDCcjd%f
class Student: private Person { ... }; // inheritance is now private w+Z};C
:y
%~9=
void eat(const Person& p); // anyone can eat ^MW%&&,BL
)/AvWDKvO
void study(const Student& s); // only students study Iq=B]oE
8WGM%n#q
Person p; // p is a Person :V2Q n-N
Student s; // s is a Student prs<ZxbQb
B<&_lG0s