2017-03-28 68 views
0

我寫了一個鏈接列表,存儲有關學生的信息。我如何將它更改爲可以存儲整數或任何其他類型的模板?我是否需要在鏈表類中重載方法,因爲他們現在需要6個參數?我的意思是,現在在年底(學生數據)插入方法是這樣的:更改鏈接列表爲模板

void insertAtEnd(int index, string name, string surname, int yearOfStudy, string fieldOfStudy, string specialty); 

如果我想存儲整數,它看起來就像這樣:

void insertAtEnd(int Data); 

所以,如果我想要使用模板來添加學生,例如整數,如果它看起來像這樣?

template <class T> 
    Class llist{ 
    void insertAtEnd(int index, string name, string surname, int yearOfStudy, string fieldOfStudy, string specialty); 
    void insertAtEnd <T Data>; 
} 

這是實現學生和LinkedList類:

class student { 
public: 
    int index; 
    string name; 
    string surname; 
    int yearOfStudy; 
    string fieldOfStudy; 
    string specialty; 
    student *next; //pointer to next item 
    student(); 
}; 

student::student() { 
next = 0; 
} 

class llist { 
    public: 
    void insertAtEnd (int index, string name, string surname, int yearOfStudy, string fieldOfStudy, string specialty); 
    void insertAtBeginning (int index, string name, string surname, int yearOfStudy, string fieldOfStudy, string specialty); 
    void insertAtGivenPosition(int a, string n, int index, string name, string surname, int yearOfStudy, string fieldOfStudy, string specialty); 
    void findStudent(int index, string surname); 
    void deleteLast(); 
    void deleteSelected(int index, string surname); 
    void deleteAll(); 
    void displayList(); 
    student *first; //pointer on first elem 
    llist(); 
}; 
+0

考慮使用'std :: list'甚至是'std :: forward_list'而不是侵入性成員。至於你的問題,我不明白你想做什麼。如果你只是想允許用戶使用*只是一個索引值,你可以簡單地使用[function overload](http://en.cppreference.com/w/cpp/language/overload_resolution)。簡而言之,如果參數足夠明確,可能會有許多具有相同名稱的函數。編譯器將爲提供給函數調用的參數使用正確的一個。 –

+0

我不得不自己實現列表,不能使用std :: forward_list。起初,我必須實施存儲學生的列表。所以我做到了,它運行良好。現在我必須用模板重做它,所以列表可以存儲任何類型的數據。 – Ensz

回答

1

在你的問題的制約,如果它在那裏,我將你的類結構變更爲:

class student { 
public: 
    int index; 
    string name; 
    string surname; 
    int yearOfStudy; 
    string fieldOfStudy; 
    string specialty; 
    //student *next; //pointer to next item 
    student(); 
}; 

template <class T> 
class node { 
    T data; 
    node<T> *next; 
} 

template <class T> 
class llist { 
public: 
    void insertAtEnd (const T &data); 
    . 
    . 
    . 
private: 
    node<T> *list; 
} 

看看上面的僞代碼,看看它/是否能回答你的問題。

0

讓你想存儲的類型構造,然後你只需要發送一個參數。或者你可以在初始化列表傳爲簡單對象: -

push({"student name", "age", major}); 

從技術上來說,這只是一個參數,假設字段匹配「學生」結構/類的順序,所以他們只爲傳遞一件事。然後,您可以輕鬆地將列表重新編碼爲模板。還是你打在推命令的構造器:

push(Student("student name", "age", major)); 

如果數據視爲一個單一的對象,然後它更容易到你的列表轉換爲一個通用的模板,因爲它與數據不再緊密耦合。數據的格式是數據對象應該處理的細節。

+0

如果你想走這條路線,你可以使用可變參數模板並支持你的類型提供的任何構造函數,而不是僅限於1個參數。 –

+0

IDK如果提問者已準備好可變模板,如果他想在此階段獲得基本列表。 –

+0

多種方式來做到這一點:我會:*不* *直接重構這個模板;相反,你需要:(1)構建一個新的基於模板的鏈表類'llist',它與'student'沒有任何關係(如果是的話;這是錯誤的)。 (2)從'student'中刪除'next'指針;它不再需要。將您現有的類更改爲'student_list',這是封裝單個成員'llist '的類。成員函數可以保持相同(或相似),但不是直接管理列表,而是主要將調用轉發給'llist '成員。這非常非常。 – WhozCraig