首頁  >  文章  >  後端開發  >  C/C++ 結構體與類別的區別

C/C++ 結構體與類別的區別

PHPz
PHPz轉載
2023-09-17 18:13:021301瀏覽

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
  • # 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++ 結構體與類別的區別的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除