英文:
operator== on C++ structs with conversion operators
问题
我试图理解当比较两个没有定义==
操作符的结构体时所涉及的==
操作符集合。在这种情况下,会使用int
的内置操作符进行转换。然而,对于嵌套类来说,例如,如果Y
包含一个定义了==
操作符的类,这种方法就不起作用。这只适用于结构体可以无歧义地转换为内置类型的情况吗?
英文:
I'm trying to understand the set of ==
operators that are explored when comparing two structs where there is no operator ==
defined. In this case the built-in operator for ints
is used for conversion. However this does not work for nested classes for example, i.e. if Y
contained a class that defined an ==
operator. Is this only applicable when a struct can be converted to a built-in type unambiguously?
struct X {
int x;
};
struct Y {
int y;
operator int() {
return y;
}
};
int main() {
// bool val {X{} == X{}}; // does not compile
bool val {Y{} == Y{}}; // works
}
答案1
得分: 2
以下是翻译好的部分:
类和结构体默认没有等于(或其他)运算符。您需要为您的实现重载所需的运算符并明确指定比较方式。
struct X {
int x;
bool operator==(const X& other) const { return x == other.x; }
bool operator!=(const X& other) const { return y != other.x; }
...
};
对于每个比较运算符(==、!=、<、>、<=、>=),都是如此,除非您使用C++20,在C++20中,您可以指定默认的<=>运算符,并让编译器为您生成它们(当然,您的结构体成员越多,这个过程就越复杂;关于比较的文档是很好的阅读材料)。
#include <compare>
struct X {
int x;
auto operator<=>(const X&) const = default;
};
英文:
Classes and structs don't have equality (or any) operators by default. You need to overload whatever is needed for your implementation and specify the comparisons explicitly.
struct X {
int x;
bool operator==(const X& other) const { return x == other.x; }
bool operator!=(const X& other) const { return y != other.x; }
...
};
That's true for every comparison operator (==, !=, <, >, <=, >=). That is unless you use C++20, in which you can specify the default <=> operator and have the compiler generate them for you (ofc the more members your struct has, the more complicated this gets; the docs on comparisons are a good read).
#include <compare>
struct X {
int x;
auto operator<=>(const X&) const = default;
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论