C++ - struct (C++軟體開發 - 結構 概念與實例)

◎基本概念
  • 是個別定義的 data type。 
  • 定義包含不同種類的Data items。 
  • 用於設計某些東西的必需有的attributes 。
◎基本範例

struct Car{
    char company[20];
    string Brand;
    double discount;
    int price;
};

int main() {
    //宣告 X5 type 為 Car
    struct Car X5, Audi;
    //擁有了type為Car,應該有的attributes  
    strcpy(X5.company,"BMW台灣總代理汎德");
    X5.Brand = "BMW汎德";
    X5.discount = 0.97;
    X5.price = 1058872;
    
    cout << "X5 company : " << X5.company << endl;
    cout << "X5 Brand : " << X5.Brand << endl;
    cout << "X5 discount : " << X5.discount << endl;
    cout << "X5 price : " << X5.price << endl;
    return 0;
}
◎pointer to  Structures
  • pointer to structure可以使用 -> operator access 成員。
◎簡單範例


struct Car{
    char company[20];
    string Brand;
    double discount;
    int price;
    struct Car *nextmodel;
};

void printCar(struct Car *model) {
    cout << "company : " << model->company << endl;
    cout << "Brand : " << model->Brand << endl;
    cout << "discount : " << model->discount << endl;
    cout << "price : " << model->price << endl;
}

int main() {
    struct Car X1, X2, X3;
    X1.nextmodel = &X2;
    X2.nextmodel = &X3;
    //擁有了type為Car,應該有的attributes  
    strcpy(X1.company, "BMW台灣總代理汎德");
    X1.Brand = "BMW汎德";
    X1.discount = 0.97;
    X1.price = 1058872;
    //pointer to structure可以使用 -> operator 指向X2
    strcpy(X1.nextmodel->company, "BMW台灣總代理汎德");
    X1.nextmodel->Brand = "BMW汎德";
    X1.nextmodel->discount = 0.97;
    X1.nextmodel->price = 1552389;
    //藉由pointer指向X3
    strcpy((*(*X1.nextmodel).nextmodel).company, "BMW台灣總代理汎德");
    (*(*X1.nextmodel).nextmodel).Brand = "BMW汎德";
    (*(*X1.nextmodel).nextmodel).discount = 0.97;
    (*(*X1.nextmodel).nextmodel).price = 1757123;
    cout << "X1-------------" << endl;
    printCar(&X1);
    cout << "X2-------------" << endl;
    printCar(X1.nextmodel);
    cout << "X3-------------" << endl;
    printCar((*X1.nextmodel).nextmodel);
    return 0;
}
◎進階範例

  • 在定義時,直接以{ }對其成員賦值。

 Car X4 = { "BMW台灣總代理汎德" ,  "BMW汎德" , 0.97, 1848358};
 printCar(&X4);

留言