别烦我啦 2023-08-28 18:23 采纳率: 71.4%
浏览 10
已结题

c++中的const函数只能由更高或相等级别的const对象调用?

在跟着教材《新标准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;
}

编译器报错

img


将MyLess类中的重载函数改为常量函数程序成功运行。但是根据报错原因,我在程序中并没有使用const类型的MyLess类调用该重载函数,想知道这是为什么

  • 写回答

3条回答 默认 最新

  • [PE]经典八炮 2023-08-28 20:25
    关注

    呃,你没使用,但是multiset内部用到了
    你点一下报错不就跳转到出错位置了?看看是不是在multiset内部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 9月6日
  • 已采纳回答 8月29日
  • 创建了问题 8月28日

悬赏问题

  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 三菱FX系列PLC串口指令
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型