九、 自訂資料型態

自訂資料型態-使用C++語言為範例

結構資料型態

結構上,有三種原則才能構成結構。

一、定義結構

結構的架構包含三個部分,分別struct 關鍵字為首的 "結構名稱",以{ } 作為範圍的"結構內容"以及結尾符號 " ; "。

struct 結構名稱{
    資料型態    資料成員1
    資料型態    資料成員2
    資料型態    資料成員3
    ...
    
    函數型態 成員函數1(參數型態 虛擬參數1, ....){
        ...
        ...
    }
    
    函數型態 成員函數2(參數型態 虛擬參數1, ....){
        ...
        ...
    }
    
};

二、宣告結構變數

結構變數使用前必須要宣告過。結構變數可為一般結構變數、結構陣列變數或是結構指標變數。

宣告結構變數語法如下

struct 結構名稱    結構變數;

三、使用結構變數

結構成員變數以及成員函數的語法。

  1. 結構變數.結構資料成員

  2. 結構變數.結構成員函數()

  3. 結構指標變數->結構資料成員

  4. 結構指標變數->結構成員函數()

結構變數是一般結構變數或是結構陣列變數時,要存取結構中的資料成員內容或使用結構中的成員函式,則必須使用結構運算子(.),若情況為指標結構運算子則為(->)。

四、巢狀結構

一個結構成員中,若有一個資料成員的資料型態為結構型態時,稱為巢狀結構。

struct  parent  
{
    string name;
    int    age;
};

struct employee
{
    int id;
    string name;
    struct parent myparent;
};

注意

定義巢狀結構時候,單層結構定義要寫在雙層結構定義上面,雙層結構定義要寫三層結構定義上面。否則會出現類似field 結構名稱 'has incomplete type'的錯誤訊息。

結構資料排序

其他陣列變數的資料不會自動相對去排列,若用結構存取這些資料型態不同且彼此間有某種關係的資料。

#include <iostream>
#include <cstdlib>
#include <string>

using  namespace std;
int main(int argc, char const *argv[])
{
    struct tel_book{
        string name;
        int age;
        string tel;
        
        void printdata(void){
            cout<< name <<'\t'
                << age  <<'\t'
                << tel  <<endl;
        }
    };
    struct tel_book telephone[3]={
        {"John",28,"04-2302"},
        {"Kate",23,"06-3402"},
        {"Issac",30,"04-8216"},
    };
    struct tel_book temp;
    
    
    cout<< " Data before sorting... " << endl;
    for(int i= 0 ; i < 3 ;i++)
        telephone[i].printdata();

    for(int i=1 ;i <=2;i++){
        for(int j=0;j<3-i;j++){
            if(telephone[j].age > telephone[j+1].age){
                temp = telephone[j];
                telephone[j] = telephone[j+1];
                telephone[j+1]=temp;
            }
        }
    }

    cout<< " Data After sorting... " << endl;
    for(int i= 0 ; i < 3 ;i++)
        telephone[i].printdata();

    return 0;
}

列舉資料型態

列舉需要有三種原則才能構成列舉。

一、定義列舉

列舉名稱的命名規則與變數相同,當列舉名稱資料型態被定義後,列舉明成就會是新資料型態。使用時候,成員名稱不可寫在=(指定運算子)的左邊。

若成員名稱1 沒有設定初始值,此項目為0

enum 列舉名稱
{
        成員名稱 1[=資料1],
        成員名稱 2[=資料2],
        ...
}

以下簡易範例

#include <iostream>
#include <cstdlib>
#include <string>

using  namespace std;

enum Is_Use{
    yes,
    no 
};

std::istream& operator>>( std::istream& is, Is_Use& i )
{
    int tmp ;
    if ( is >> tmp )
        i = static_cast<Is_Use>( tmp ) ;
    return is ;
}

int main(int argc, char const *argv[])
{

    enum Is_Use use;
    cin >> use;
    if(use==yes){
        cout << use <<": Yes";
    }
    if(use==no){
        cout << use<<": No";
    }
    
    return 0;
}

若遇到compiler無法成功,可以嘗試用下方function

std::istream& operator>>( std::istream& is, Is_Use& i )
{
    int tmp ;
    if ( is >> tmp )
        i = static_cast<Is_Use>( tmp ) ;
    return is ;
}

最后更新于

这有帮助吗?