結構體(struct)是將不同類型、不同長度的數據元素(成員)組合成一個自定義類型。語法:
struct TypeName {
Type1 member1;
Type2 member2;
// ...
} objectList;
// 定義類型 product,聲明三個對象
struct product {
int weight;
double price;
} apple, banana, melon;
// 分離定義與聲明
struct product { int weight; double price; };
product apple, banana, melon;
// 匿名結構體直接聲明對象
struct { int weight; double price; } apple, banana, melon;
用點運算符 . 訪問對象成員:
apple.weight = 100; apple.price = 5.5; cout << apple.weight << " " << apple.price;
#include#include #include using namespace std; struct Movie { string title; int year; }; void printMovie(Movie m) { cout << m.title << " (" << m.year << ")\n"; } int main() { Movie mine = {"2001 A Space Odyssey", 1968}; Movie yours; string mystr; cout << "Enter title: "; getline(cin, yours.title); cout << "Enter year: "; getline(cin, mystr); stringstream(mystr) >> yours.year; cout << "My favorite:\n"; printMovie(mine); cout << "Yours:\n"; printMovie(yours); return 0; }
Movie films[3];
for (int i=0; i<3; i++) {
getline(cin, films[i].title);
getline(cin, mystr); stringstream(mystr) >> films[i].year;
}
for (int i=0; i<3; i++) printMovie(films[i]);
結構體是 C++ 面向對象的基石,將相關數據聚合為邏輯單元。成員可為任意類型(包括結構體、指針、數組)。掌握定義、實例化、成員訪問、數組應用是進階數據結構學習的前提。