声明一个std :: map迭代器会导致一个奇怪的错误

use*_*747 2 c++ stl std map

我只是想声明一个map迭代器但是我得到一个编译错误,说"预期;在它之前"

我相信这是因为我没有包含整个std命名空间(使用命名空间std;)但我故意不想包含所有这些.

我的代码:

#include <map>
#include <string>

template <class Object>
class Cont
{
    public:
       Cont() {}
       Object* get( unsigned int nID )
       {
           std::map <unsigned int, Object*>::iterator it = m.begin(); // error here "expected ; before it" what is this error?

           for ( ; it != m.end(); it++ ) 
           {
               if ( (*it).second->ID == nID ) { return (*it).second; }
           }

           return NULL;
       }

       std::map <unsigned int, Object*> m;
};
Run Code Online (Sandbox Code Playgroud)

我试过这个但是它不起作用:

std::map <unsigned int, Object*>::std::iterator it = m.begin();
Run Code Online (Sandbox Code Playgroud)

GWW*_*GWW 12

如果我没有弄错,因为你正在使用模板参数,你需要在迭代器声明前加上typename.

typename std::map <unsigned int, Object*>::iterator it = m.begin();
Run Code Online (Sandbox Code Playgroud)

  • 我发现typename的这个[讨论](http://pages.cs.wisc.edu/~driscoll/typename.html)有助于理解为什么以及何时需要typename关键字. (3认同)