|
|
发表于 2012-2-11 21:01:55
|
显示全部楼层
- #include <iostream>
- #include <map>
- using namespace std;
- class A
- {
- private:
- int a;
- public:
- A(int _a):a(_a){}
- bool operator >(A s)
- {
- return (this->a>s.a);
- }
- void show() const
- {
- cout<<"a="<<a<<endl;
- }
- };
- class B
- {
- public:
- bool operator () (A a,A b)
- {
- return (a>b);
- }
- };
- void display(map<A,int,B> s)
- {
- map<A,int,B>::iterator it;
- for(it=s.begin();it!=s.end();it++)
- {
- (it->first).show();
- }
- }
- int main()
- {
- map<A,int,B> c1;
- c1.insert(map<A,int,B>::value_type(A(1),1));
- c1.insert(pair<A,int>(A(2),2));
- display(c1);
- return 0;
- }
复制代码 把void show()改为void show() const
因为map的键是不可改变的,所以it->first的类型是const A&,因此只能调用const成员函数
此外你自己看看,很多成员函数都可以写为const成员函数,你都没有写,这些函数都存在类似的隐患 |
|