首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ 數據結構基礎(一):結構體定義與使用

     編輯:C++ 入門

結構體概念

結構體(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++ 面向對象的基石,將相關數據聚合為邏輯單元。成員可為任意類型(包括結構體、指針、數組)。掌握定義、實例化、成員訪問、數組應用是進階數據結構學習的前提。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved