c++继承中的对象模型

我们知道继承方式有三种

public,protect,private

不同继承方式,在子类中有些是不可以访问的

那么我们想知道到底子类继承了多少?

看代码做一下验证

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 class father
 5 {
 6 public:
 7     int a;
 8 protected:
 9     int b;
10 private:
11     int c;
12 };
13 
14 class son1:public father
15 {
16 public:
17     int d;
18 };
19 
20 class son2:protected father
21 {
22 public:
23     int d;
24 };
25 
26 class son3:private father
27 {
28 public:
29     int d;
30 };
31 void test()
32 {
33     son1 s1;
34     cout << "size of s1 is " << sizeof(s1) << endl;
35 
36     son2 s2;
37     cout << "size of s2 is " << sizeof(s2) << endl;
38 
39     son3 s3;
40     cout << "size of s3 is " << sizeof(s3) << endl;
41 }
42 
43 int main()
44 {
45     test();
46     return 0;
47 }

无论何种继承都是16,也就是说父类的东西都继承下来了。只是有些访问权限

需要注意,private 继承方式。虽然基类的public 和 protected 成员在子类中都变成了private

但是子类仍然可以访问,而原来的private是不能访问的

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 class father
 5 {
 6     public:
 7         int a = 1;
 8     protected:
 9         int b = 2;
10     private:
11         int c = 3;        
12 };
13 
14 class son:private father
15 {
16        public:
17            int d = 4;
18            void f()
19            {
20                cout << this->a << endl;
21                cout << this->b << endl;
22         }
23 };
24 
25 void test()
26 {
27     son s1;
28     s1.f();
29 }
30 
31 int main()
32 {
33     test();
34     return 0;
35 }
View Code

原文地址:https://www.cnblogs.com/mch5201314/p/11594007.html