博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
struct vs class in C++
阅读量:4348 次
发布时间:2019-06-07

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

 

  在C++中,除了以下几点外,struct和class是相同的。

  (1)class的成员的默认访问控制是private,而struct的成员的默认访问权限是public。

  例如,program 1会编译失败,而program 2可正常运行。

 

1 // Program 1 2 #include 
3 4 class Test 5 { 6 int x; // x is private 7 }; 8 9 int main()10 {11 Test t;12 t.x = 20; // compiler error because x is private13 getchar();14 return 0;15 }16 17 // Program 218 #include
19 20 struct Test 21 {22 int x; // x is public23 };24 25 int main()26 {27 Test t;28 t.x = 20; // works fine because x is public29 getchar();30 return 0;31 }

 

 

  (2)在继承体系中,当struct继承自struct/class时,对于base struct/class的默认访问控制是public。但当class继承自struct/class时,对base struct/class的默认访问控制是private。

  例如,program 3会编译失败,而program 4可正常运行。

1 // Program 3 2 #include 
3 4 class Base 5 { 6 public: 7 int x; 8 }; 9 10 class Derived : Base 11 { 12 }; // is equilalent to class Derived : private Base {}13 14 int main()15 {16 Derived d;17 d.x = 20; // compiler error becuase inheritance is private18 getchar();19 return 0;20 }21 22 // Program 423 #include
24 25 class Base 26 {27 public:28 int x;29 };30 31 struct Derived : Base 32 { 33 }; // is equilalent to struct Derived : public Base {}34 35 int main()36 {37 Derived d;38 d.x = 20; // works fine becuase inheritance is public39 getchar();40 return 0;41 }

 

  总结:

  对于struct和class的不同点就在于:默认访问控制不同,struct为public,class为private。

  而这个不同体现在两个地方:一是成员的默认访问控制;二是继承体系中对基类的默认访问控制。

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

 

 

 

 

 

 

  转载请注明:

  2013-11-25  19:52:01

转载于:https://www.cnblogs.com/iloveyouforever/p/3442118.html

你可能感兴趣的文章
47 【golang】mysql操作
查看>>
Using ARITHABORT with LLBLGen
查看>>
增量模型与快速模型的异同。
查看>>
Hanoi双塔问题(简单的枚举)
查看>>
lattice 黑盒子的生成和使用(Creating Your Own Black Box Modules)
查看>>
SONIC from microsoft&Azure,one project of OCP
查看>>
NDK以及C语言基础语法(一)
查看>>
ES6/ES2015核心内容 import export
查看>>
pid参数调节的几句话
查看>>
Day4-文件,json字典文件互转,函数
查看>>
.Net core 使用Jenkins + Docker + Azure Devops 持续部署(CI/CD)
查看>>
C#基础(数据类型运算符)
查看>>
pinyin4j的基本使用
查看>>
linux copy
查看>>
原生js实现音乐列表(隔行换色、全选)
查看>>
docker hub 本地镜像登录
查看>>
图论学习二之Topological Sort(拓扑排序)
查看>>
android图片压缩的3种方法实例
查看>>
Careercup - Microsoft面试题 - 4639756264669184
查看>>
B - Broken Keyboard (a.k.a. Beiju Text)
查看>>