
在C++中,结构和类基本相同。但也有一些细微的差别。这些差异如下所示。
默认情况下,类成员是私有的,但结构体的成员是公共的。让我们看看这两个代码,看看有什么不同。
示例
#include using namespace std;class my_class { int x = 10;};int main() { my_class my_ob; cout << my_ob.x;}
输出
This program will not be compiled. It will generate compile time error forthe private data member.
示例
#include using namespace std;struct my_struct { int x = 10;};int main() { my_struct my_ob; cout << my_ob.x;}
输出
10
When we derive a structure from a class or structure, the default access specifier of that base class is public, but when we deriving a class the default access specifier is private.
示例
#include using namespace std;class my_base_class { public: int x = 10;};class my_derived_class : my_base_class {};int main() { my_derived_class d; cout << d.x;}
输出
This program will not be compiled. It will generate compile time error that the variable x of the base class is inaccessible
示例
#include using namespace std;class my_base_class { public: int x = 10;};struct my_derived_struct : my_base_class {};int main() { my_derived_struct d; cout << d.x;}
输出
10
以上就是C/C++ 结构体与类的区别的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1445371.html
微信扫一扫
支付宝扫一扫