2 c++ struct operator-overloading operators
我有一个结构,我想通过定义<,>,<=和> =运算符来定义相对顺序.实际上在我的顺序中不会有任何相等,所以如果一个结构不小于另一个结构,它会自动变大.
我像这样定义了第一个运算符:
struct MyStruct{
...
...
bool operator < (const MyStruct &b) const {return (somefancycomputation);}
};
Run Code Online (Sandbox Code Playgroud)
现在我想基于这个运算符定义其他运算符,这样<=将返回与<相同的返回值,而其他两个运算符将只返回oposite.所以例如对于>运算符我想写类似的东西
bool operator > (const MyStruct &b) const {return !(self<b);}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何引用这个"自我",因为我只能参考当前结构中的字段.
整个是在C++中
希望我的问题是可以理解的:)
感谢您的帮助!
如果您提供了operator<所有适当的逻辑(无论它是否作为自由函数实现),您可以将其他运算符作为自由函数实现.这遵循以下规则:在可能的情况下优先选择非成员而不是成员,并且自由函数将具有与左右操作数的转换相同的行为,而作为成员函数实现的运算符则不然.
例如
inline bool operator>(const MyStruct& a, const MyStruct&b)
{
return b < a;
}
inline bool operator<=(const MyStruct& a, const MyStruct&b)
{
return !(b < a);
}
inline bool operator>=(const MyStruct& a, const MyStruct&b)
{
return !(a < b);
}
Run Code Online (Sandbox Code Playgroud)