2016-12-03 81 views
0

我在使用模板類和列表時遇到了一個問題,這裏是代碼。我收到的錯誤都是在同一行和事情就像語法錯誤,它說的printList非法使用類型爲void,另一個錯誤是無法識別的模板聲明/定義模板類T與列表的錯誤

#include <iostream> 
#include <list> 
#include <deque> 
#include <functional> 
#include <algorithm> 

using namespace std; 

template<class T> 
void printList<T>(const list& lst, string s) { 

cout << s << ": "; 
for (typename list::const_iterator i = lst.begin(); i != lst.end(); i++) 
cout << *i << " "; 
cout << endl; 
} 

它不斷給我的錯誤與void printList<T>線可有人可以幫我找出爲什麼會發生這種情況嗎?

+0

你是否真的需要所有這些主線來證明問題? –

+0

抱歉。我刪除了不必要的代碼 – zachstarnes

+1

使用'名單'那就是你有'list'和刪除錯誤放置''。 –

回答

0

聲明函數普通的方法是:

template<class T> 
void printList(const list<T>& lst, string s) 

您還需要改變

cout << s << endl; 

cout << s.c_str() << endl; 

以上典雅只是

#include <string> 

還有

list::const_iterator 

list<T>::const_iterator 

否則你不聲明你的列表對象的模板類型。

+0

非常感謝你! – zachstarnes

+0

'cout << s.c_str()<< endl;'不正確。 '''''''''''cout'可以很好地工作。 –

+0

我的意思是s.c_str()的作品...,他將需要使用s.c_str()或包括他的代碼編譯(至少在我的編譯器)。 – aah