我需要定义`operator ==`才能使用标准容器类吗? [英] Do I need to define `operator==` to use my class with standard containers?
问题描述
我找不到等效的定义。这意味着我必须定义 operator ==
作为我的类的成员,所以 T(x)== x
返回true?
(为了避免诸如暗示运算符==
必须定义之类的事情;在一般情况下不会这样。)
但是,如果他们的数据表示相同的对象,概念上两个东西是等效的。如果一个类有复制时可能不同的数据,那么你需要做一个运算符==
(可能 operator<
以及 rel_ops
),以确保相对于此实现了等效。 (实际上,请确保可变数据不是类的一部分。)
通常最好不要去这样的路由,因为你最终必须修补很多东西,以确保它的正常工作。如果要复制的东西,让我们完全复制。这更有意义。
I'd like clarification on the C++ standard, specifically where it says (my interpretation) in section 20.1.3 that "for class T and an instance of class T called x, T(x) must be equivalent to x" for the class to work with standard containers.
I couldn't find a definition of 'equivalent'. Does this mean that I have to define operator==
as a member of my class, so that T(x) == x
returns true?
Equivalent is purposefully vague. (To avoid things like implying operator==
must be defined; it doesn't in a general case.)
However, conceptually two things are equivalent if their data represents the same object. If a class has data that might be different when "copied", then you do need to make an operator==
(and possibly operator<
along with rel_ops
) to make sure that "equivalent" is implemented with respect to that. (Effectively, make sure that the mutable data isn't 'part of the class', so to speak.)
It's usually better not to go such a route, because you end up having to patch lots of things up to make sure it works properly. If something is to be copied, let if be fully copied. This makes much more sense.
这篇关于我需要定义`operator ==`才能使用标准容器类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!