[cpp]C++中類和結構體的區別

C++中結構體和類的區別

在C++中,結構體和類基本一致,除了小部分不同。主要的不同是在訪問的安全性上。

  1. 在類中默認的訪問權限是private,而結構體是public。
  2. 當從基類/結構體中派生時,類的默認派生方式是private,而結構體是public。

實例

#include <stdio.h> 
  
class Test { 
    int x; // x是private 
}; 
int main() 
{ 
  Test t; 
  t.x = 20; // 編譯錯誤,因爲x是私有的
  getchar(); 
  return 0; 
} 

// Program 2 
#include <stdio.h> 

struct Test { 
	int x; // x 是public 
}; 
int main() 
{ 
Test t; 
t.x = 20; // 編譯正確 
getchar(); 
return 0; 
} 


// Program 3 
#include <stdio.h> 

class Base { 
public: 
	int x; 
}; 

class Derived : Base { }; //相當於是private派生

int main() 
{ 
Derived d; 
d.x = 20; //編譯錯誤,因爲是private派生來的 
getchar(); 
return 0; 
} 


// Program 4 
#include <stdio.h> 

class Base { 
public: 
	int x; 
}; 

struct Derived : Base { }; // 相當於是public派生

int main() 
{ 
Derived d; 
d.x = 20; // 編譯正確
getchar(); 
return 0; 
} 

參考

https://www.geeksforgeeks.org/structure-vs-class-in-cpp/?ref=lbp

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章