C/C++ 结构与类

cc++server side programmingprogramming更新于 2024/9/7 15:47:00

在 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
  • 当我们从一个类或结构派生出一个结构时,该基类的默认访问说明符是 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

相关文章