首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于模板的一个有关问题

2012-04-24 
关于模板的一个问题写了段小程序老是报错,大家帮忙看下#include map#include stringusing namespace s

关于模板的一个问题
写了段小程序老是报错,大家帮忙看下
#include <map>
#include <string>

using namespace std;

template <class T>
class test
{
public:
  void add(const char* index, T* data);
  void remove(const char* index);
  int getSize();
private:
  map<string, T*> m_map;
};

template <class T>
int test<T>::getSize()
{
  return m_map.size();
}

template <class T>
void test<T>::add(const char* index, T* data)
{
  m_map[index] = data;
}

template <class T>
void test<T>::remove(const char* index)
{
  map<string, T*>::iterator it = m_map.find(index);

  if ( it != m_map.end() )
  {
  delete (T*)(it->second);
  m_map.erase(it);
  }
}

int main()
{
  test<int> a;
  return 0;
}

编译错误:
g++ -o a template.cpp 
template.cpp: In member function ‘void test<T>::remove(const char*)’:
template.cpp:33: error: expected `;' before ‘it’
template.cpp:35: error: ‘it’ was not declared in this scop

[解决办法]
把这句

C/C++ code
map<string, T*>::iterator it = m_map.find(index);
[解决办法]
如ls那样改.
因为在模板函数里面或者类里面, 编译器无法知道::之后的是一个类型还是一个变量.
如你上面错误的iterator,你得在前面加typename 告诉编译器,这是个变量,编译器才会知道.

热点排行