/*条款39:明智而审慎地使用private继承*/
#include<iostream>
using namespace std;
class Person{};
class Student :private Person{};//私有继承
void eat(const Person&p){}
void study(const Student&s){}
class Timer{
public:
explicit Timer(int tickFrequency);
virtual void onTick()const;
};
/*class Widget :private Timer{
private:
virtual void onTick()const;
};*/
class Widget{
private:
class WidgetTimer :public Timer{//相对上个私继承方法,这个使用了继承与复合,并引入了新的内部类
public:
virtual void onTick()const;//Widget的子类无法取用WidgetTimer,因此不法继承它或重新定义它的虚函数
};
WidgetTimer timer;
};
//---------
class Empty{};
class HoldAnInt{
private:
int x;
Empty e;//应该不需要任何内存
};
class HoldAnInt1:private Empty{//私有继承的优点 :空白基类最优化,一般只在单一继承下才可行
private:
int x;
};
int main(){
Person p;
Student s;
eat(p);
/*eat(s);//学生不能吃东西,学生不是人?? 对!
如果继承关系是private
1 编译器不会自动将一个子类对象转换为一个基类对象
2 子类继承来的所有成员在子类中全部变成私有
3 private 继承意味着 is-implemented-in-terms-of
*/
cout << "sizeof(Empty)" << sizeof(Empty) << " sizeof(HoldAnInt):" << sizeof(HoldAnInt) << endl;
cout << "sizeof(Empty)" << sizeof(Empty) << " sizeof(HoldAnInt1):" << sizeof(HoldAnInt1) << endl;
/*
私有继承意味着is-implemented-in-terms of 比复合级别低 ,但是子类需要访问基类保护成员,或需要重新定义继承而来的虚函数时,这么设计合理
*/
system("pause");
return 0;
}