我是否需要定义“operator==”才能将我的类与标准容器一起使用?

发布于 2024-09-10 06:44:11 字数 186 浏览 9 评论 0原文

我想澄清 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

少跟Wǒ拽 2024-09-17 06:44:11

等价物故意含糊不清。 (为了避免暗示 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 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.

风吹短裙飘 2024-09-17 06:44:11

这意味着该类应该是可复制构造的。
并且复制构造函数创建一个与原始对象等效的对象。

如果您没有定义,编译器将生成一个复制构造函数。
如果类不包含任何指针,则在大多数情况下应该可以正常工作。

注意:您不需要定义“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 =='

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文