note: say ‘typename std::list::const_iterator’ if a type is meant

STL常见疑难杂症

note: say ‘typename std::list::const_iterator’ if a type is meant

分析原因:

注意:任何时候在模板(template)中使用一个嵌套从属类型名称, 需要在前一个位置, 添加关键字typename;
比如上例中使用迭代器类型时,就要使用typename.虽然在vs2010 和vs2015中没有错误,但在VC++2019和gcc编译器中,都会报错。

例子:

// demo 15_42_疑难杂症  
#include <iostream>
#include <deque>
#include <string>
#include <vector>
#include <list>

using namespace std;

template <typename T>
void printInf(const list<T>& object) throw()
{
	string line(50, '-');
	list<T>::const_iterator citor;
	for (citor = object.begin(); citor != object.end(); citor++) {
		cout << *citor << endl;
	}
	cout << endl;
	cout << "size:" << object.size() << endl;
	cout << line << endl;
	return;
}

class Student
{
public:
	Student() {
		cout << "默认构造函数" << endl;
		this->m_nAge = 0;
		this->m_sName = "未知";
	}
	Student(int _age, const char* _name) {
		cout << "带参数的构造函数" << endl;
		this->m_nAge = _age;
		this->m_sName = _name;
	}
	Student(const Student& object) {
		cout << "拷贝构造函数" << endl;
		this->m_nAge = object.m_nAge;
		this->m_sName = object.m_sName;
	}
	~Student() {
		cout << "析构函数 " << endl;
	}
	friend ostream& operator<<(ostream& out, const Student& stu);
public:
	string	m_sName;
	int		m_nAge;
};

ostream& operator<<(ostream& out, const Student& stu) {
	out << "年龄:" << stu.m_nAge << "\t" << "姓名:" << stu.m_sName;
	return out;
}

int main(int agrc, char** argv)
{
	Student s1(21, "张大帅");
	Student s2(21, "李小美");
	Student s3(51, "张三");
	Student s4(50, "罗二");
	
	list<Student> stuList;

	printInf<Student>(stuList);

	system("pause");
	return 0;
}

运行环境: centos.6.9
运行结果:
在这里插入图片描述

解决方案:

在 list 前面加 typename

typename list<T>::const_iterator citor;

运行结果:
在这里插入图片描述

发布了35 篇原创文章 · 获赞 33 · 访问量 299

猜你喜欢

转载自blog.csdn.net/m0_45867846/article/details/105481341