zoukankan      html  css  js  c++  java
  • error C2678: 二进制“<”: 没有找到接受“const _Ty”类型的左操作数的运算符

    今日老友问我一个 c艹 的报错问题,如下两个版本,一个对,一个错:
    可以编译通过:

    #include <algorithm>
    #include <iostream>
    using namespace std;
    struct Stu
    { 
    	int age;
    	bool operator<(const Stu& s)
    	{
    		return age > s.age;
    	}
    };
    int main()
    {
    	Stu arr[2];
    	arr[0].age = 6;
    	arr[1].age = 8;
    	sort(arr, arr + 2); // [arr,arr+2)
    	for (auto& item : arr)
    	{
    		cout << item.age << ' ' ;
    	}
    
    	return 0;
    }
    

    如上正常使用,没有报错。
    我们知道 sort 缺省函数为 less,如下模板类:

    template<>
    struct less<void>
    	{	// transparent functor for operator<
    	typedef int is_transparent;
    	template<class _Ty1,
    		class _Ty2>
    		constexpr auto operator()(_Ty1&& _Left, _Ty2&& _Right) const
    		-> decltype(static_cast<_Ty1&&>(_Left)
    			< static_cast<_Ty2&&>(_Right))
    		{	// transparently apply operator< to operands
    		return (static_cast<_Ty1&&>(_Left)  < static_cast<_Ty2&&>(_Right));
    		}
    	};
    

    重点看这句话,参数类型非 const。

    auto operator()(_Ty1&& _Left, _Ty2&& _Right)
    

    然后我们再看下文报错的情况


    但是如果老友使用 set 函数:
    error C2678: 二进制“<”: 没有找到接受“const _Ty”类型的左操作数的运算符(或没有可接受的转换)

    #include <set>
    #include <algorithm>
    #include <iostream>
    using namespace std;
    struct Stu
    { 
    	int age;
    	bool operator<(const Stu& s) 
    	{
    		return age > s.age;
    	}
    };
    int main()
    {
    	set<Stu> my_set;
    	my_set.insert(Stu{ 6 });
    	my_set.insert(Stu{ 8 });
    
    	for (auto& item : my_set)
    	{
    		cout << item.age << ' ' ;
    	}
    
    	return 0;
    }
    

    修改以下,可以编译通过了:

    bool operator<(const Stu& s) const // 添加 const
    

    老友问我为什么?
    我们可以通过观察报错说明来看:
    有一句话:编译 类 模板 成员函数 "bool std::less<_Kty>::operator ()(const _Ty &,const _Ty &) const" 时******
    因为我们自定义了 Stu 类的排序规则,即重载了 operator<.

    Set 内部排序缺省函数位 less
    我们去看一下类模板 less

    template<class _Ty = void>
    struct less
    {	// functor for operator<
          constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const
          {	        // apply operator< to operands
    		return (_Left < _Right);
           }
    };
    

    看到参数是 const _Ty& _Left, const _Ty& _Right,所以传入的 this 对象引用变成 const _Ty& _Left,而 _Left 是 const 导致无法调用非 cosnt 成员函数 opertator<。所以需要添加 const 使其变成 const 成员函数

    关于const的作用:
    表示成员函数隐含传入的this指针为const指针
    后面加 const表示函数不可以修改class的成员
    https://blog.csdn.net/SMF0504/article/details/52311207

  • 相关阅读:
    Seq命令的用法
    Vsftp的PASV mode(被动模式传送)和Port模式及 Linux下VsFTP配置全方案
    PHP网页截图网页快照实现
    MimeType资料
    SQl 周报表 周统计
    IsolatedStorageFile 配额等
    SQL 月报表
    参数编码 完全解决方案
    File,FileStream,byte[]3者互相转换总结(转)
    SL 在 IE8下显示的高度变小 解决方法
  • 原文地址:https://www.cnblogs.com/KongHuZi/p/13823350.html
Copyright © 2011-2022 走看看