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.

示例代码

 实际演示

#include <iostream>
using namespace std;
struct my_struct{
   int x = 10;
};
int main() {
   my_struct my_ob;
   cout << my_ob.x;
}

输出

10

当我们从类或结构派生一个结构时,该基类的默认访问说明符是公共的,但是当我们派生一个类时,默认访问说明符是私有的。

示例代码

 实际演示

#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

更新日期: 30-Jul-2019

185 次浏览

启动你的 职业

完成课程以获得认证

开始
广告
© . All rights reserved.