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.