private继承

private继承的意思是“根据某物实现出”,是一种“has-a”的关系。而不像public继承那样继承了接口,是一种“is-a”的关系。

private继承一般可以通过复合来代替,但也有些情况会比复合更好

 1 #include<iostream>
 2 using namespace std;
 3 class Time{
 4 protected:
 5     virtual void print()
 6     {
 7         cout<<"Record time:"<<endl;
 8     }
 9     void Reset()
10     {}
11 };
12 class Widget:private Time{
13     char ch;
14 public:
15     void print() 
16     {
17         Time::print();
18         cout<<"This is widget time"<<endl;
19     }
20 };
21 int main()
22 {
23     Widget w;
24     w.print();
25     cout<<sizeof(Widget)<<endl;
26     return 0;
27 }
View Code

程序运行输出是:

Record time:

This is widget time

8(有了vptr后会进行内存对齐)

用private继承,Widget可以重写Time类的虚函数,但并没有继承Time类的Reset接口

posted @ 2016-04-04 12:06  vaevaevae  阅读(351)  评论(0编辑  收藏  举报