您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/3/21 7:57:50发布36次查看
在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 forthe 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++ 结构体与类的区别的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product