[英]Adding function templates to classes
到目前為止,我已經實現了一個基本的 LinkedList。 這有效,但僅適用於整數,我希望它適用於任何類型。
我試圖讓它首先適用於任何相同類型(即只有字符串的 LinkedList,或者只有整數)。 之后,我希望它找到一種方法,使其成為任何東西的 LinkedList(包含字符串,然后是整數,然后是長整數,全部在一個列表中)。
#include <iostream>
struct Node{
Node(int value);
Node *next;
int data;
};
Node::Node(int value){
this->data = value;
this->next = nullptr;
}
struct LinkedList{
Node *head;
LinkedList();
void push_back(int value);
void print();
};
LinkedList::LinkedList(){
this->head = nullptr;
}
void LinkedList::push_back(int value){
Node *n = new Node(value);
if(this->head == nullptr){
this->head = n;
} else {
Node *cursor = this->head;
while (cursor->next != nullptr){
cursor = cursor->next;
}
cursor->next = n;
}
}
void LinkedList::print(){
Node *cursor = this->head;
while(cursor != nullptr){
std::cout << cursor->data << '\n';
cursor = cursor->next;
}
}
int main(){
LinkedList l = LinkedList();
l.push_back(1);
l.push_back(2);
l.print();
}
但是,以上僅適用於整數。 我知道,但我認為方法是使用模板,但是,這樣做,我似乎做得太過分了? 它不編譯? 有清潔工是這樣做的嗎?
#include <iostream>
template <typename T>
struct Node {
Node(T value);
int data;
Node<T> *next;
};
template <typename T>
Node<T>::Node(T value){
this->next = nullptr;
this->data = value;
}
template <typename T>
class LinkedList{
public:
LinkedList();
Node<T> *head;
void push_back(T data);
void print();
};
template <typename T>
LinkedList<T>::LinkedList(){
this->head = nullptr;
}
template <typename T>
void LinkedList<T>::push_back(T data){
Node *n = new Node(data);
if(this->head == nullptr){
this->head = n;
} else {
Node *cursor = this->head;
while(cursor->next != nullptr){
cursor = cursor->next;
}
cursor->next = n;
}
}
template <typename T>
void LinkedList<T>::print(){
Node *cursor = this->head;
while(cursor != nullptr){
std::cout << cursor->data << '\n';
cursor = cursor->next;
}
}
int main(){
LinkedList<T> *list = new LinkedList<T>();
list->push_back(1);
list->push_back(2);
list->push_back(3);
}
在聲明模板類時,您在聲明和實現中使用“T”作為“類型占位符”(正如您所做的那樣)。 但是,當您想要實際使用模板化類的對象時,您可以將“T”替換為您想要的實際類型。
所以,在你的main
(假設你想要一個int
類型),你會有這樣的代碼:
int main(){
LinkedList<int> *list = new LinkedList<int>(); // THIS object uses "int" wherever "T" occurs in the declaration/implementation
list->push_back(1);
list->push_back(2);
list->push_back(3);
}
我還注意到您的struct
聲明中有一個“可能的/可能的錯誤”,您在其中指定data
成員的(固定)類型為int
; 也許(幾乎可以肯定,實際上,當您稍后為其分配一個“T”類型的value
時)您希望它根據請求的實際類型而有所不同? 如果是這樣,請進行以下更改:
template <typename T>
struct Node {
Node(T value);
// int data;
T data; // Data will be whatever "T" is when an object is created.
Node<T> *next;
};
隨時要求進一步澄清和/或解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.