博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c++继承中的对象模型
阅读量:4695 次
发布时间:2019-06-09

本文共 1420 字,大约阅读时间需要 4 分钟。

我们知道继承方式有三种

public,protect,private

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

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

看代码做一下验证

1 #include
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 father15 {16 public:17 int d;18 };19 20 class son2:protected father21 {22 public:23 int d;24 };25 26 class son3:private father27 {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
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 father15 {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

你可能感兴趣的文章
Unity多开的方法
查看>>
File类中的list()和listFiles()方法
查看>>
我的VS CODE插件配置 主要针对.NET和前端插件配置
查看>>
关于js中的事件
查看>>
一致性哈希算法运用到分布式
查看>>
决策树和随机森林->信息熵和条件熵
查看>>
iOS10 UI教程视图和子视图的可见性
查看>>
Maven学习笔记
查看>>
FindChildControl与FindComponent
查看>>
1、简述在java网络编程中,服务端程序与客户端程序的具体开发步骤?
查看>>
C# Web版报表
查看>>
中国城市json
查看>>
android下载手动下载Android SDK
查看>>
北京邮电大学 程序设计课程设计 电梯 文件输入版本(已调试,大致正确运行==)...
查看>>
C++学习:任意合法状态下汉诺塔的移动(原创)
查看>>
学霸修炼的秘籍
查看>>
Duplicate 复制数据库 搭建Dataguard
查看>>
leetcode133 - Clone Graph - medium
查看>>
Mybatis(一)入门
查看>>
DDR工作原理(转)
查看>>