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.

示例

#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

更新於: 2019 年 7 月 30 日

312 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.