在《C++箴言:确保公开继承模拟“is-a”》一文中论述了 C++ 将 public inheritance(公有继承)视为一个 is-a 关系。当给定一个 hierarchy(继承体系),其中有一个 class Student 从一个 class Person 公有继承,当为一个函数调用的成功而有必要时,需要将 Students 隐式转型为 Persons,它通过向编译器展示来做到这一点。用 private inheritance(私有继承)代替 public inheritance(公有继承)把这个例子的一部分重做一下是值得的: v0LGdX)/Y
G3a7`CD
class Person { ... }; wxdyF&U
n
class Student: private Person { ... }; // inheritance is now private :kG)sw7
iKAusWj
void eat(const Person& p); // anyone can eat 3i=Iu0
|8U;m:AS
void study(const Student& s); // only students study !Z|($21W
qINTCm j
Person p; // p is a Person 6Hf,6>
Student s; // s is a Student ,b|-rU\
zk}{ dG^M:
eat(p); // fine, p is a Person L;/n!k.A
G%:GeW
eat(s); // error! a Student isn't a Person &