我用 C++ 实现了一个简单的 STL 映射。按照我的指示将比较分解为一种类型,然后实现如下所示的比较:
template <typename T> int KeyCompare<T>::operator () (T tKey1, T tKey2)
{
if(tKey1 < tKey2)
return -1;
else if(tKey1 > tKey2)
return 1;
else
return 0;
}
在这里,tKey1 和 tKet2 是我要比较的两个键。这适用于所有基本数据类型和字符串。我添加了一个模板特化来比较名为Test的用户定义类型的键,并添加了一个特化如下:
int KeyCompare<Test>::operator () (Test tKey1, Test tKey2)
{
if(tKey1.a < tKey2.a)
return -1;
else if(tKey1.a > tKey2.a)
return 1;
else
return 0;
}
当我运行它时,我收到一个链接错误说
SimpleMap.obj : 错误 LNK2005: "public: int __thiscall KeyCompare::operator()(class Test,class Test)" (??R?$KeyCompare@VTest@@@@QAEHVTest@@0@Z) 已经在 MapTest 中定义.obj
SimpleMap.obj : 错误 LNK2005: "public: __thiscall KeyCompare::~KeyCompare(void)" (??1?$KeyCompare@VTest@@@@QAE@XZ) 已在 MapTest.obj 中定义
SimpleMap.obj : error LNK2005: "public: __thiscall KeyCompare::KeyCompare(void)" (??0?$KeyCompare@VTester@@@@QAE@XZ) 已在 MapTest.obj 中定义
MapTest.cpp 是我在其中编写测试用例的测试工具类。我也使用了包含守卫,以阻止多个包含。
知道怎么回事吗??
非常感谢你!!