Aimy

关于c++的私有继承,不可访问

c++私有继承其实并不常用,因为私有继承会使其派生类访问属性变为private或是不可访问,

我们现在要说的就是这个不可访问,其实这个不可访问应该叫不可直接访问,其实不可直接访问成员是可以通过一定方法访问的,所以我们叫他不可直接访问。

上代码:

 1 #include <iostream>
 2 
 3 using std::cout;
 4 using std::cin;
 5 using std::endl;
 6 
 7 // 类 A 为基类
 8 class A{
 9 public:
10     A(int m):a(m){}
11     void getA()
12     {
13         cout<< a <<endl;
14     }
15 private:
16     int a;
17 };
18 
19 
20 class B: private A
21 {
22 public:
23     B(int m):A(m){}  // 类B调用类A的构造函数A()并传入参数m
24 
25     void getB(void)
26     {
27         getA();
28     }
29 };
30 
31 
32 class C: private B
33 {
34 public:
35     C(int m):B(m){}  // 类C调用类B的构造函数B()并传入参数m
36 
37     void getC(void)
38     {
39         getB();
40     }
41 };
42 
43 int main(void)
44 {
45     C c(0);    // 实例化对象c, 传入参数m
46     c.getC();  // 输出的为类A的私有数据成员 a 
47 
48     system("PAUSE");
49     return 0;
50 }

可是这样是不是太麻烦了,所以一般我们是不用private继承的,通常是public继承

posted @ 2012-11-27 22:26  一只小小的菜鸟1  阅读(1451)  评论(0编辑  收藏  举报