stl set使用时,passing ‘const xxx’ as ‘this’ argument of 'xxx 'discards qualifiers 丢弃限定符的问题

看下面的代码有什么问题?

#include <stdio.h>
#include <set>

class test
{
public:
    int data;
    bool operator < (const test& dst)
    {   
        return data < dst.data;
    }   
    void set_data( int param)
    {   
        data = param;
    }   
};

int main()
{
    std::set<test> test_set;
    test a;
    a.data = 1;
    test_set.insert(a);
    std::set<test>::iterator it; 
    for(it = test_set.begin(); it != test_set.end(); it++)
        it->set_data(2);
    return 0;
}

g++ test.cpp -o test -g 编译错误如下:

test.cpp:26: error: passing ‘const test’ as ‘this’ argument of ‘void test::set_data(int)’ discards qualifiers

/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h:227: error: passing ‘const test’ as ‘this’ argument of ‘bool test::operator<(const test&)’ discards qualifiers


原因是:

set 返回的对象永远都是const类型,所以 it指向的只是const test,而it->set_data(2)会改变data,与const冲突。

解决方案:

代码如下:

#include <stdio.h>
#include <set>

class test
{
public:
    int data;
    bool operator < (const test& dst) const
    {   
        return data < dst.data;
    }   
    void set_data( int param)
    {   
        data = param;
    }   
};

class test_cmp_fun
{
public:
    bool operator() ( const test* t1, const test* t2) const
    {   
        return (*t1) < (*t2);
    }   
};

int main()
{
    std::set<test*, test_cmp_fun> test_set;
    test *pa = new test;
    pa->data = 1;
    test_set.insert(pa);
    std::set<test*, test_cmp_fun>::iterator it; 
    for(it = test_set.begin(); it != test_set.end(); it++)
        (*it)->set_data(2);
    printf("%d\n", pa->data);
    delete pa; 
    return 0;
}

这里用了一个比较函数,而set存放的是指针,如果不用比较函数,set就会自动比较指针的值,显然和笔者要求的不同,注意最后要delete

你可能感兴趣的:(delete,iterator,Class,fun,DST)