重载类中的<运算符
overloading the < operator inside a class
我正在尝试使用一个简单的结构作为映射键:
class Foo{
.
.
.
struct index{
int x;
int y;
int z;
};
bool operator<(const index a, const index b);
.
.
.
}
以及它的功能:
bool Foo::operator<(const index a, const index b){
bool out = True;
if (a.x == b.x){
if (a.y == b.y){
if (a.z >= b.z) out = false;
}
else if(a.y > b.y) out = false;
} else if (a.x > b.x) out = false;
return out;
}
然而,当我编译时,我得到了一个错误:
memMC.h:35:错误:'bool Foo::operator<(Foo::index,Foo::index)'必须只接受一个参数
据我所知,编译器希望将index
与此Foo
进行比较。那么我该如何让操作员过载呢?
如果要比较两个索引,请在index
结构中移动重载:
struct index{
int x;
int y;
int z;
bool operator<(const index& a) const;
};
如果你想比较Foo
和index
(我对此表示怀疑,但我只是把它放在这里以防万一),删除第二个参数,因为它不需要:
class Foo{
//...
bool operator<(const index& a) const;
};
请注意,应该通过引用传递index
参数,以防止不必要的复制。
编辑:正如Als正确指出的,这个运算符应该是const
。
<
是二进制中缀比较运算符,即它需要两个参数来相互比较。因此,理想情况下,它应该作为一个自由函数来实现。但是,如果您将其作为成员函数来实现,那么它只需要一个参数。
它应将作为参数传递的参数与调用成员函数的对象进行比较。
你的会员比较操作员应该是这样的:
class Foo
{
//...
bool operator<(const index& rhs) const
{
/* comparison with *this */
}
//...
};
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多