首页 > 后端开发 > C++ > 正文

C/C++ 结构体与类的区别

PHPz
发布: 2023-09-17 18:13:02
转载
1608人浏览过

c/c++ 结构体与类的区别

在C++中,结构和类基本相同。但也有一些细微的差别。这些差异如下所示。

  • 默认情况下,类成员是私有的,但结构体的成员是公共的。让我们看看这两个代码,看看有什么不同。

    C知道
    C知道

    CSDN推出的一款AI技术问答工具

    C知道 45
    查看详情 C知道

示例

#include <iostream>
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 for
the private data member.
登录后复制

示例

#include <iostream>
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 <iostream>
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 <iostream>
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++ 结构体与类的区别的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号