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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值