天天看点

Missing 'typename' prior to dependent type name 'list<int>::iterator'

文章目录

      • 1.在依赖类型"XXXX::XX"前缺少typename关键字
      • 2.例子

1.在依赖类型"XXXX::XX"前缺少typename关键字

  • 这个问题产生原因是编译器不能识别"XXXX::XX"是个啥,这到底是个类型呢,还是类得静态成员变量呢?
  • 解决方法也很简单就是在"XXXX::XX"前面加上typename,告诉编译器这是个类型。

2.例子

  • 这是我准备用模板写的一个复用list遍历,然后就报这个错。
  • 报错代码:
#include <iostream>
#include <list>
using namespace std;

template <class T>

void showlist(list<T> v)
{
    for ( list<T>::iterator it = v.begin(); it != v.end(); it++)//报错
    {
        cout << *it;
    }
    cout << endl;
}

int main()
{

    list<int> l1{ 1,2,3,4,5,5,6,7,7 };
    showlist(l1);
    list<double> l2;
    list<char> l3(10);
    list<int> l4(5, 10); //将元素都初始化为10
    showlist(l4);   
    return 0;
}
           
  • 改正代码:
#include <iostream>
#include <list>
using namespace std;

template <class T>

void showlist(list<T> v)
{

    typename list<T>::iterator it;
    for ( it = v.begin(); it != v.end(); it++)
    {
        cout << *it;
    }
    cout << endl;
}

int main()
{

    list<int> l1{ 1,2,3,4,5,5,6,7,7 };
    showlist(l1);
    list<double> l2;
    list<char> l3(10);
    list<int> l4(5, 10); //将元素都初始化为10
    showlist(l4);
    return 0;
}
           

继续阅读