IDE
Microsoft Visual Studio Community 2019
错误列表
错误代码
#include <iostream>
#include <list>
using namespace std;
template <typename T>
void output_list(list<T> lst) {
list<T>::iterator it = lst.begin(); // 错误语句
for (; it != lst.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
int main() {
list<int> lstInt;
for (int i = 0; i < 15; i++) {
lstInt.push_back(i);
}
cout << "lst : ";
output_list(lstInt);
return 0;
}
正确代码
#include <iostream>
#include <list>
using namespace std;
template <typename T>
void output_list(list<T> lst) {
typename list<T>::iterator it = lst.begin(); // 正确语句 - 给错误语句添加"typename"
for (; it != lst.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
int main() {
list<int> lstInt;
for (int i = 0; i < 15; i++) {
lstInt.push_back(i);
}
cout << "lst : ";
output_list(lstInt);
return 0;
}
疑问
类型从属名称的使用必须以“typename”为前缀,是什么意思呢?