C/C++ 结构体与类
在 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.
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include <iostream> using namespace std; struct my_struct { int x = 10; }; int main() { my_struct my_ob; cout << my_ob.x; }
输出
10
当我们从类或结构派生一个结构时,基类的默认访问说明符是 public,但当我们派生一个类时,则默认访问说明符是 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
广告