在跟着教材《新标准c++程序设计》这本书写代码时,按照他的代码打上去出现关于const限定级别的错误。
#include<iostream>
#include<set>
using namespace std;
template<class T>
void Print(T first, T last) {
for (; first != last; ++first) {
cout << *first << " ";
}
cout << endl;
}
class A {
private:
int n;
public:
A(int n_) { n = n_; }
friend bool operator<(const A& a1, const A& a2) {
//友元函数也可以在类内定义但不属于类的成员函数,而是一般外界函数,同理友元函数没有this指针
return a1.n < a2.n;
}
friend ostream& operator<<(ostream& o, const A& a2) {
o << a2.n; return o;
}
friend class MyLess;
};
class MyLess {
public:
bool operator()(const A& a1, const A& a2){
return (a1.n % 10) < (a2.n % 10);
}
};
typedef multiset<A> MSET1;
typedef multiset<A, MyLess> MSET2;
int main() {
const int SIZE = 6;
A a[SIZE] = { 4,22,19,8,33,40 };
MSET1 m1;
m1.insert(a, a + SIZE);
m1.insert(22);
cout << "1)" << m1.count(22) << endl;
cout << "2)"; Print(m1.begin(), m1.end());
MSET1::iterator pp = m1.find(19);
if (pp != m1.end())
cout << "found" << endl;
cout << "3)"; cout << *m1.lower_bound(22) << "," << *m1.upper_bound(22) << endl;
pp = m1.erase(m1.lower_bound(22), m1.upper_bound(22));
cout << "4)"; Print(m1.begin(), m1.end());
cout << "5)"; cout << *pp << endl;
MSET2 m2;
m2.insert(a, a + SIZE);
cout << "6)"; Print(m2.begin(), m2.end());
return 0;
}
编译器报错
将MyLess类中的重载函数改为常量函数程序成功运行。但是根据报错原因,我在程序中并没有使用const类型的MyLess类调用该重载函数,想知道这是为什么