c++ 函数模板问题
#include<iostream>#include<list>#include<algorithm>usingnamespacestd;template<typenam...
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
template <typename Type>
ostream & operator<<(ostream & out, const list<Type> & aList)
{
for (list<Type>::const_iterator it = aList.begin(); it != aList.end(); it++)
out << *it << " ";
return out;
}
int main()
{
list<int> la, lb(4, 111), lc(6);
int array[] = {2, 22, 222, 2222};
list<int> ld(array, array + 4);
cout << "la: " << la << "---size = " << la.size() << endl;
cout << "lb: " << lb << "---size = " << lb.size() << endl;
cout << "lc: " << lc << "---size = " << lc.size() << endl;
cout << "ld: " << ld << "---size = " << ld.size() << endl;
}
编译时提示模板定义处有错误,但是怎么找也看不出哪里有错误,望高人指教
我如果不用模板声明那个函数,而直接把int类型写进函数声明中去,这个程序就好使,不知道为什么不能用模板声明 展开
#include <list>
#include <algorithm>
using namespace std;
template <typename Type>
ostream & operator<<(ostream & out, const list<Type> & aList)
{
for (list<Type>::const_iterator it = aList.begin(); it != aList.end(); it++)
out << *it << " ";
return out;
}
int main()
{
list<int> la, lb(4, 111), lc(6);
int array[] = {2, 22, 222, 2222};
list<int> ld(array, array + 4);
cout << "la: " << la << "---size = " << la.size() << endl;
cout << "lb: " << lb << "---size = " << lb.size() << endl;
cout << "lc: " << lc << "---size = " << lc.size() << endl;
cout << "ld: " << ld << "---size = " << ld.size() << endl;
}
编译时提示模板定义处有错误,但是怎么找也看不出哪里有错误,望高人指教
我如果不用模板声明那个函数,而直接把int类型写进函数声明中去,这个程序就好使,不知道为什么不能用模板声明 展开
2个回答
展开全部
for (list<Type>::const_iterator it = aList.begin(); it != aList.end(); it++)
->
for (typename list<Type>::const_iterator it = aList.begin(); it != aList.end(); it++)
旧点的编译器好像能编译,
加个typename 指明 list<Type>::const_iterator 为类型试试
->
for (typename list<Type>::const_iterator it = aList.begin(); it != aList.end(); it++)
旧点的编译器好像能编译,
加个typename 指明 list<Type>::const_iterator 为类型试试
追问
确实好使,非常感谢
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询