C3848 VS2022错误原因

在学习C++STL中的set时,尝试利用仿函数,改变set的排序规则,代码如下

#include<iostream>
#include<cstring>
#include<algorithm>
#include<set>
using namespace std;

class Mypx {
public:
    bool operator() (int a, int b) {
        return a > b;
    }
    
};
void test01() {
   set<int,Mypx> s1;
    s1.insert(10);
    s1.insert(20);
    s1.insert(40);
    s1.insert(30);
    for (set<int,Mypx>::iterator it = s1.begin(); it != s1.end(); it++) {
        cout << *it << ' ';
    }
}

int main() {
    test01();
}

编译器报错
错误 C3848 具有类型“const Mypx”的表达式会丢失一些 const-volatile 限定符以调用“bool Mypx::operator ()(int,int)” Project2 C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.36.32532\include\xutility 1160

解决方法
在仿函数中,重载()的函数后面加const

class Mypx {
public:
    bool operator() (int a, int b)  const{
        return a > b;
    }
};

原因

  • 安全性:通过声明成员函数为const,可以确保在该函数内部不会对类的数据成员进行修改,从而提高代码的安全性。

  • 可用性:当您在const对象上调用一个const成员函数时,可以确信这个函数不会引起对象状态的改变,这使得在使用const对象时也能够使用这个函数。

  • 清晰性:标记成员函数为const可以使其接口更清晰地表明其行为,其他开发人员在使用和阅读代码时可以更容易地理解函数的作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值