該程式的目標是使用模板來創建通用串列。我的 DoublyLinkedList.cpp 檔案采用泛型型別,然后以鏈表方式存盤元素。無論如何,我無法讓我的主函式初始化串列。我的一些代碼可以在下面找到。
int main(int argv, char* argv[])
{
cout << "Enter list type (i = int, f = float, s = std:string)";
char listType;
cin >> listType;
if (listType == 'i')
{
DoublyLinkedList<int>* list = new DoublyLinkedList<int>();
}
else if (listType == 'f')
{
DoublyLinkedList<float>* list = new DoublyLinkedList<float>();
}
else
{
DoublyLinkedList<string>* list = new DoublyLinkedList<string>();
}
(*list).print();
}
uj5u.com熱心網友回復:
由于這個網站既無用又無用,我只是自己弄明白了。我發現實作此目的的最佳方法是在 main.cpp 中創建一個函式,該函式接受一個模板并使用那里的物件實作所有函式。
void testList(DoublyLinkedList<T>* list)
{
(*list).print();
}
int main(int argv, char* argv[])
{
cout << "Enter list type (i = int, f = float, s = std:string)";
char listType;
cin >> listType;
if (listType == 'i')
{
DoublyLinkedList<int>* list = new DoublyLinkedList<int>();
testList(list);
}
else if (listType == 'f')
{
DoublyLinkedList<float>* list = new DoublyLinkedList<float>();
testList(list);
}
else
{
DoublyLinkedList<string>* list = new DoublyLinkedList<string>();
testList(list);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/326461.html
