我正在尝试使用自定义比较器,如以下最小示例所示:
#include <set>
using namespace std;
struct idComp;
class TestClass
{
public:
int id;
void setId(int i){ id = i; }
int getId(){ return id; }
void test( set<TestClass*, idComp> &s){
//do my stuff
}
void test2(){
set <TestClass*, idComp> s;
}
};
struct idComp
{
bool operator() (TestClass* t1, TestClass* t2) const
{
return t1->getId() < t2->getId();
}
};
int main(int argc, char* argv[])
{
return 0;
}
但当我试图编译时,我得到了以下与test
函数有关的错误:
comp_ref.cpp:12:34: error: ‘idComp’ was not declared in this scope
void test( set<TestClass*, idComp> &s){
^~~~~~
comp_ref.cpp:12:40: error: template argument 2 is invalid
void test( set<TestClass*, idComp> &s){
加上test2
:
/usr/include/c++/7/bits/stl_tree.h:708:31: error: invalid use of incomplete type ‘struct idComp’
_Rb_tree_impl<_Compare> _M_impl;
关于如何/在哪里定义idComp
以使其可由函数test
使用,有什么建议吗?
由于您有一点循环依赖关系,因此可以通过在TestClass
:之前前向声明idComp
来解决此问题
struct idComp;
class TestClass
{
...
但是你可以把struct idComp
的定义留在它所在的地方