返回列表 發帖

【6-2】struct (一)

本帖最後由 教學組 於 2025-4-29 17:34 編輯

在C++中struct(結構)是一種自定義的資料類型,可以將不同類型的資料組合在一起成為一個單一的個體。struct與class(類別)功能相同,兩者主要的差別在預設的存取權限,struct預設是public而class預設是private,因此當只是用來表示純粹的資料結構而不是設計完整的物件導向類別時,使用struct更為簡單方便。

在建置物件時,除了可用為各個屬性指派值的方式,也可用建構函式來為物件初始化。初始化列表是一種特殊的建構函式語法,我們可運用初始化列表更加簡潔地在建置物件的同時為物件初始化。

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct Dog
  4. {
  5.     string name;
  6.     int age;
  7.     float w;
  8.     void showProfile()
  9.     {
  10.         cout<<name<<"今年"<<age<<"歲,體重"<<w<<"公斤。"<<endl;
  11.     }
  12.     void makeSound(int n)
  13.     {
  14.         for(int i=0; i<n; i++)
  15.             cout<<"汪~";
  16.         cout<<endl;
  17.     }
  18. };
  19. struct Cat
  20. {
  21.     //屬性 / 成員變數
  22.     string name;
  23.     int age;
  24.     float w;

  25.     //Cat(): name(""), age(0), w(0) {}  //不帶任何參數的初始化列表 / 建構函式

  26.     Cat(string n, int a, float w): name(n), age(a), w(w) {}  //初始化列表 / 建構函式

  27.     /*
  28.     Cat(string n, int a, float w)  //建構函式
  29.     {
  30.         name=n;
  31.         age=a;
  32.         this->w=w;  //當變數名稱相同時,需以 this-> 語法來描述屬於物件的變數,或乾脆將名稱設為不同。
  33.     }*/

  34.     //方法 / 成員函式
  35.     void showProfile()
  36.     {
  37.         cout<<name<<"今年"<<age<<"歲,體重"<<w<<"公斤。"<<endl;
  38.     }
  39.     void makeSound(int n)
  40.     {
  41.         for(int i=0; i<n; i++)
  42.             cout<<"喵~";
  43.         cout<<endl;
  44.     }
  45. };
  46. int main()
  47. {
  48.     Dog d=Dog();  //使用預設的建構函式建立物件
  49.     d.name="憨憨";   //初始化物件
  50.     d.age=2;
  51.     d.w=3.6;
  52.     d.showProfile();
  53.     d.makeSound(3);

  54.     //Cat c=Cat();   //當自定了帶參數的建構函式,預設的建構函式就會失效,若有使用需求則必須再自行定義。

  55.     Cat c=Cat("咪咪", 3, 2.7);   //使用自定的建構函式建立同時初始化物件
  56.     c.showProfile();
  57.     c.makeSound(5);

  58.     return 0;
  59. }
複製代碼

返回列表