注册 登录
编程论坛 C++教室

c++函数对象

来生再见 发布于 2016-03-26 02:31, 3458 次点击
程序代码:

#include <iostream>
using namespace std;

#include <map>
#include <string>

template <typename T>
class MyGreater
{
public:
    bool operator()(T& left,T& right)
    {
        return left > right;
    }
};

int main(int argc, char *argv[])
{
    map<int, string, MyGreater<int> > maptest;
    maptest.insert(pair<int,string>(1,"aaa"));
    return 0;
}

问一下那个函数对象怎么使用不了呢?
3 回复
#2
rjsp2016-03-29 08:32
bool operator()(T& left,T& right)
改为
bool operator()(const T& left, const T& right) const;
#3
苍穹之舞2016-03-31 10:34
以下是引用rjsp在2016-3-29 08:32:44的发言:

bool operator()(T& left,T& right)
改为
bool operator()(const T& left, const T& right) const;

为毛要加const ?

他不变?
#4
rjsp2016-03-31 11:21
回复 3楼 苍穹之舞
map 中的 key 是不可以更改的

即使它可以更改,但你不需要更改它,也应该使用const
1