错误信息 :
C3848 具有类型“const myComp”的表达式会丢失一些 const-volatile 限定符以调用“bool myComp::operator ()(int,int)”
代码段为:
class myComp {
public:
bool operator()(int v1, int v2) {
return v1 > v2;
}
};
void set04() {
//指定排序规则为从大到小
set<int,myComp>s2;
//插入数据
s2.insert(20);
s2.insert(10);
s2.insert(40);
s2.insert(30);
for (set<int,myComp>::const_iterator it = s2.begin(); it != s2.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
错误原因 (个人理解):函数隐含传入的this 指针为const 指针,因此在成员函数中修改它所在类的成员的操作都是不被允许的。
解决方案 :在仿函数中加入 const
class myComp {
public:
bool operator()(int v1, int v2) const { //在这加
return v1 > v2;
}
};