我是否需要定义“operator==”才能将我的类与标准容器一起使用?
我想澄清 C++ 标准,特别是第 20.1.3 节中所说的(我的解释)“对于类 T 和名为 x 的类 T 的实例,T(x) 必须等于该类的 x”使用标准容器。
我找不到“等效”的定义。这是否意味着我必须将 operator==
定义为我的类的成员,以便 T(x) == x
返回 true?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
等价物故意含糊不清。 (为了避免暗示
operator==
必须 被定义;一般情况下不会。)但是,从概念上讲,如果两个事物的数据表示相同,则它们是等效的目的。如果一个类的数据在“复制”时可能会有所不同,那么您确实需要创建一个
operator==
(可能还需要operator<
以及rel_ops< /code>) 以确保“等效”已实现。 (实际上,可以这么说,确保可变数据不是“类的一部分”。)
通常最好不要走这样的路线,因为您最终必须修补很多东西以确保它有效适当地。如果要复制某些内容,请完全复制。这更有意义。
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 possiblyoperator<
along withrel_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 ==
”This means the class should be copy constructable.
And that the copy constructor creates an object that is equivelent to the original.
If you do not define one the compiler will generate a copy constructor.
If the class does not contain any pointers this should work fine in most situations.
Note: You do not need to define the '
operator ==
'