结构向量 - 没有看到我对运算符==的定义
Vector of structs - not seeing my definition for operator==
我有一个名为Something的类,它有两个东西:一个字符串和一个指令向量。在该类中,我想定义运算符==。但是,当我尝试编译时出现错误:
error: no match for ‘operator==’ in ‘* __first1 == * __first2’
这发生在我使用 == 比较 Something 中的两个向量的行(因为向量有方便的定义,我想使用它)。
说明如下:
struct instruction
{
int instr;
int line;
bool operator==(const instruction& rhs)
{
return (instr == rhs.instr) && (line == rhs.line);
}
};
我一直在寻找解决方案无济于事。似乎来自 STL 的向量在比较这些元素时没有看到我为我的结构定义的运算符==。
您尚未显示实际失败的代码,但很可能是如下所示的情况:
int main()
{
vector <instruction> ins;
vector <instruction>::const_iterator itA = /*...*/, itB = /*...*/;
bool b = (*itA == *itB);
}
在这种情况下,问题是operator==
不const
。 更改声明,如下所示:
bool operator==(const instruction& rhs) const
^^^^^^^
尝试将限定符 const 添加到运算符 ==。此外,您没有展示如何声明和使用向量。
你可能想让 operator=() 方法本身变得 const。 您可以通过添加"const"来做到这一点:
struct instruction
{
int instr;
int line;
bool operator==(const instruction& rhs) const // add const keyword here
{
return (instr == rhs.instr) && (line == rhs.line);
}
};
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 如何正确实现和访问运算符的各种自定义枚举器
- 自定义先决条件对移动分配运算符有效吗
- 在运算符重载定义中使用成员函数(const错误)
- g++用户定义的动态链接库上的全局new和delete运算符
- 一元"运算符"未在C++中定义
- STL按客户"<"运算符对向量进行排序。为什么要将"<"运算符定义为 const?
- 如何将运算符定义从头文件添加到现有结构?
- 在使用具有相等运算符定义的抽象类时,如何定义父类以减少代码重复?
- 当我们没有将运算符+定义为朋友时?C++
- 没有返回值的c++类成员运算符定义
- 用指向对象的指针和c++中的new运算符定义对象
- <T> 仅为具有运算符/定义的此类 T 创建模板
- 基类中的运算符定义
- C++:不同名称空间中的多个运算符定义
- 运算符定义不能正常工作
- 类运算符'='定义
- 为什么VS不为逻辑运算符定义可选的令牌?
- std::equal_range 不适用于具有运算符<定义的结构