C++错误C3848:具有类型“XXX”的表达式会丢失一些 const-volatile 限定符以调用“XXX”

问题:

在练习map容器时,对其做自定义顺序排序时出现错误

环境:

Visual Studio 2019

错误:

C3848 具有类型“const MyCompare”的表达式会丢失一些 const-volatile 限定符以调用“bool MyCompare::operator ()(int,int)”

代码:
#include<iostream>
#include<map>

using namespace std;

class MyCompare
{
public:
	bool operator()(int v1, int v2)
	{
		return v1 > v2;
	}
};

void test01()
{
	map<int, int, MyCompare>m;

	m.insert(make_pair(1, 10));
	m.insert(make_pair(2, 20));
	m.insert(make_pair(3, 30));
	m.insert(make_pair(4, 40));
	m.insert(make_pair(5, 50));

	for (map<int, int, MyCompare>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << it->first << " " << it->second << endl;
	}
}

int main()
{
	test01();

	return 0;
}
解决:

于是打开百度搜索,在这篇文章中找到了解决办法

在仿函数中加入const

class MyCompare
{
public:
	bool operator()(int v1, int v2) const
	{
		return v1 > v2;
	}
};

然后就可正常运行
运行结果

思考:

但是疑惑的地方在于,我这是按照老师所写代码敲出来的,为什么老师可以正常运行

视频地址

右键显示错误帮助,看到微软给出的

微软错误帮助
然后我把代码拿到Code::Blocks中运行,发现没有错误,正常运行

个人理解应该是Visual Studio的编译器对此做出了更新,要求必须使用const限定。

  • 37
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值