我已经实现了operator<
对于某个对象。
逻辑上,如果 !(a < b)
和 !(b < a)
这意味着a == b
.
这是自动推断的吗?我可以使用 ==
如果我只实现 <
?
最佳答案
C++ 无法自动推断这一点有几个原因:
- 将每种类型都与
operator<
进行比较是没有意义的,因此类型不一定定义为operator<
.- 这意味着
operator==
不能根据operator<
自动定义
- 这意味着
-
operator<
不需要比较它的论点。程序员可以为他们的类型定义运算符,以便对他们的参数做几乎任何事情。- 这意味着您关于
!(a < b) && !(b < a)
的声明相当于a == b
假设这些运算符已定义,则不一定正确。
- 这意味着您关于
如果您想要 operator==
您的类型的功能,只需自己定义一个。没那么难:)
// For comparing, something like this is used
bool operator==(const MyType& lhs, const MyType& rhs)
{
// compare (or do other things!) however you want
}
// ... though it's not the only thing you can do
// - The return type can be customised
// - ... as can both of the arguments
const MyType& operator==(int* lhs, const MyType* const rhs)
{
return lhs;
}
关于c++ - 如果我只实现运算符 <,我可以使用运算符 == 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44129275/