找不到'=='运算符,该运算符采用const Type的左操作数 [英] No '==' operator found which takes a left-hand operand of const Type

查看:140
本文介绍了找不到'=='运算符,该运算符采用const Type的左操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构我的一些代码,以使用结构而不是单个对象.

I was refactoring some of my code to use a structure instead of a single object.

由于此更改,我需要为'=='添加运算符,以便我现有的包含函数的向量可以正确地评估存储在向量中的对象.

As a result of this change I needed to add in the operator for '==' so my existing vector involving functions could correctly evaluate my objects stored in the vectors.

class IdentifyingClass; //forward declare class     
Class ReturnData
{
public:
  IdentifyingClass* value;
  float  some_trivial_additional_data;

  bool operator==(const ReturnData& query_obj)
  {
    return value == query_obj.value;
  }

  bool operator==(const IdentifyingClass* query_obj)
  {
    return value == query_obj;
  }
}

我所有依赖此类的现有代码均正常运行.我认为这是一个开放和封闭的重构.

All my existing code that relied on this class was functioning correctly. I thought it was an open and shut refactor.

然后,在使用该类类型的特定边缘情况下,在不同解决方案的其他地方使用了它.我正在尝试使用此

Then I had use of it in a different place in a different solution in a specific edge case that used this class type. I was attempting to use this

IdentifyingClass* object;
const std::vector<ReturnData>& data_vector = GetDataFromPlace();
if(std::find(data_vector.begin(), data_vector.end(), object) != data_vector.end()))
{
  //do special action;
}

现在,我正在生成向量'=='比较错误,告诉我我没有"const ReturnData"的左手"=="操作数.

Now I was generating a vector '==' comparison error telling me I didn't have a left-hand '==' operand of "const ReturnData".

推荐答案

我很困惑地尝试了一些事情,以了解为什么当我的参数显然在处理const时,运算符不是const的原因.

I tried a few things while looking with bafflement as to why the operator wasn't const when clearly my parameters were handling const.

到了我将上面的代码更改为使用std :: find_if并使用lambda作为谓词来将代码解析为所需功能的地步.

It got to the point where I changed my above code to use std::find_if and used a lambda as my predicate to resolve the code to the functionality I wanted.

真正的问题是我的运算符未标记为const:

The real issue was my operators were not marked const:

bool operator==(const ReturnData& query_obj) const
{
  return value == query_obj.value;
}

bool operator==(const IdentifyingClass* query_obj) const
{
  return value == query_obj;
}

之所以将这个相当琐碎的问题写成一个堆栈溢出的帖子,是因为我发现与此类似的其他帖子仅着重强调了那些帖子的其他问题,而不是这个特定的案例,这确实花了一些时间.

The reason I have made this rather trivial issue into a stack overflow post is that other posts I have found similar to this only highlight other issues with those posts and not this specific case, which did take a little while to spot.

本期与我相关的热门文章:

Top related posts of my issue:

向量是const对象

Typedef和名称空间问题

这篇关于找不到'=='运算符,该运算符采用const Type的左操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆