看下面的代码有什么问题?
#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; }
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; }