簡介#
在 C++ 中,struct(結構)是一種自定義的資料類型,將不同的資料類型組合在一起形成一個新的資料類型。struct 中可以包含變數、函式等等,非常適合用來表示一個物件。
struct 和 class 的區別
如果你有學過其他語言,你可能會發現 struct 和 class 非常相似,確實他們都能達到差不多的目的。但是在 C++ 中,struct 和 class 之間的唯一區別是預設的成員訪問權限。在 struct 中,所有的成員變數和成員函式預設都是 public 的,而在 class 中,預設是 private 的。
定義一個 struct#
如果想要使用 struct,首先需要寫一個 struct 關鍵字,然後定義結構體的名稱,語法如下:
struct student {
}
這樣我們就有一個空的結構體了,就像其他變數型態一樣,你可以這樣宣告你的 student:
int main() {
struct student s1;
}
也可以把 struct 關鍵字簡寫掉:
int main() {
student s1;
}
這樣我們就成功宣告了一個空的 student 結構體了,雖然目前看起來還沒什麼用,但是接下來我們會看到 struct 的強大之處!
定義成員變數#
接下來,我們要來定義結構體的成員變數,這樣我們才能再結構體中儲存資料。定義成員變數的方法和定義普通變數一樣,只是在結構體中定義而已:
struct 結構體名稱 {
成員變數類型1 成員變數1;
成員變數類型2 成員變數2;
};
這邊是一個簡單的例子:
struct student {
string name; // 學生姓名
int age; // 學生年齡
double grade; // 學生成績
};
在這個例子中,我們定義了一個 student 結構體,包含了三個成員變數 name、age 和 grade,分別用來儲存學生的姓名、年齡和成績。接下來讓我們來把這個結構體宣告出來,並嘗試存取和修改它的成員變數:
int main() {
student s1;
s1.name = "John";
s1.age = 20;
cout << s1.name << endl; // John
cout << s1.age << endl; // 20
s1.name = "Alice";
s1.grade = 3.8;
cout << s1.name << endl; // Alice
cout << s1.grade << endl; // 3.8
}
就像這樣,我們可以透過 . 來存取和修改結構體的成員變數。
修改整個結構體#
如果你想要修改整個結構體的值,你可以透過大括號 {} 來直接賦值:
int main() {
student s1 = {"John", 20, 3.8};
cout << s1.name << endl; // John
cout << s1.age << endl; // 20
cout << s1.grade << endl; // 3.8
s1 = {"Alice", 22, 4.0};
cout << s1.name << endl; // Alice
cout << s1.age << endl; // 22
cout << s1.grade << endl; // 4.0
}
大括號裡面的值要按照宣告時的順序來填入,並且類型必須吻合。
定義函式#
在使用 struct 的時候還要一直定外部的函式來操作它不覺得很不直觀嗎?別擔心,我們還可以在 struct 中定義「成員函式」來操作結構體變數:
struct 結構體名稱 {
成員變數類型 成員變數1;
成員變數類型 成員變數2;
成員函式類型 成員函式1() {
// 函式實作
}
成員函式類型 成員函式2() {
// 函式實作
}
};
這邊是一個例子:
#include <bits/stdc++.h>
using namespace std;
struct student {
string name;
int age;
double grade;
// 成員函式
void say_hi() {
cout << "Hi, my name is " << name << endl;
}
};
int main() {
student s1 = {"John", 20, 3.8};
s1.say_hi(); // Hi, my name is John
}
struct 作為函式參數和返回值#
struct 變數可以作為函式的參數和返回值進行傳遞,這在處理複雜的資料結構時特別有用!(尤其是學校程式專題做遊戲的時候)
#include <bits/stdc++.h>
using namespace std;
struct student {
string name;
int age;
double grade;
};
// 以 struct 作為參數
void print_student(student s) {
cout << "Name: " << s.name << endl;
cout << "Age: " << s.age << endl;
cout << "Grade: " << s.grade << endl;
}
// 以 struct 作為返回值
student create_student(string name, int age, double grade) {
student s;
s.name = name;
s.age = age;
s.grade = grade;
return s;
}
int main() {
student s1 = create_student("John", 20, 3.8);
print_student(s1);
}
在這個範例中:
print_student()函式接受一個student物件作為參數,然後輸出它的成員變數值。create_student()函式根據傳入的參數創建一個新的student物件,並將其作為返回值返回。
