大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
public 派生被称为类型继承(type inheritance),反映了一种(is-a) "是一种"关系。
private 派生被称为实现继承(implementation inheritance ),基类非private成员在派生类中都是private,供派生类使用。(基类的private在派生类中无法访问)
class A
{
public:
    
void fun(){cout<<"A::fun"<<endl;}
}
;

//private inheritance
class B: private A
{
public:
    
void use_fun(){fun();}
}
;

//protected inheritance
class C: protected A
{

}
;

class D: public C
{
public:
    
void use_fun(){fun();}
}
;


int main()
{
    B b;
    
//A*p = &b;        //can not assign, B is not A
    
//b.fun();        //error, A::fun is private in B
    b.use_fun();

    C c;
    
//A *p = &c;    //can not assign, C is not A
    
//c.fun();        //error A::fun is protected in C

    D d;
    d.use_fun();
    
return 0;
}


免除:
通过使用关键字using, 可以使基类成员免除私有继承的影响。
class A
{
public:
    
void fun(){cout<<"A::fun"<<endl;}
}
;

//private inheritance
class B: private A
{
public:
    
void use_fun(){fun();}
    
using A::fun;        //exempting
}
;

    B b;
    b.fun();        
//ok
posted on 2009-06-02 11:30 大胖 阅读(134) 评论(0)  编辑 收藏 引用 所属分类: C++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理