# Different between struct and class in cpp 在 C++ 中,struct(結構體)是一種用來建立自訂資料型別的工具,可以把多個不同型別的資料包在一起。這在處理一組有邏輯關聯的資料時非常有用。 ## ✅ 基本語法 ```cpp struct Point { int x; int y; }; ``` 這樣就定義了一個名叫 Point 的結構體,裡面有兩個整數成員:x 和 y。 使用方法如下: ```cpp int main() { Point p1; // 宣告一個 Point 型別的變數 p1 p1.x = 3; p1.y = 4; cout << p1.x << ", " << p1.y << endl; // 輸出:3, 4 } ``` ## ⚠️ C 與 C++ 的差異 在 C 語言 中,使用時要加上 struct: ```c struct Point p1; ``` 在 C++ 中則不需要,可以直接寫: ```cpp Point p1; ``` ## ✅ struct 也可以有函式(C++ 擴充) C++ 中,struct 和 class 幾乎一樣,唯一差別是: - struct 預設成員為 public - class 預設成員為 private ```cpp struct Point { int x, y; void move(int dx, int dy) { x += dx; y += dy; } }; int main() { Point p = {1, 2}; p.move(3, 4); cout << p.x << ", " << p.y << endl; // 4, 6 } ``` ## ✅ struct 可以搭配 constructor(建構子) ```cpp struct Point { int x, y; Point(int a, int b) { x = a; y = b; } }; ``` 使用: ```cpp Point p(5, 6); ``` ## 📌 總結 | 功能 | 說明 | | --------------- | -------------------------------------- | | 成員變數 | 可以定義多個資料欄位 | | 建構子/成員函式 | C++ 中支援,和 class 一樣 | | 存取權限 | struct 預設 public;class 預設 private | | 使用場景 | 簡單資料封裝時常用;class 用於完整 OOP |
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up