优秀的编程知识分享平台

网站首页 > 技术文章 正文

不要定义虚函数类型的比较运算符(列出不同类型的联想意义并加以定义英语答案解析)

nanyue 2024-07-18 03:49:26 技术文章 6 ℃

C.87: Beware of == on base classes

C.87:小心基类的相等运算符

Reason(原因)

It is really hard to write a foolproof and useful == for a hierarchy.

为继承体系写出简单又好用的相等运算符真的很难。

Example, bad(反面示例)

class B {
 ? ?string name;
 ? ?int number;
 ? ?virtual bool operator==(const B& a) const
 ? ?{
 ? ? ? ? return name == a.name && number == a.number;
 ? ?}
 ? ?// ...
};

B's comparison accepts conversions for its second operand, but not its first.

B的相等比较运算符的第二个操作数接受类型转换,但是第一个不行。

class D :B {
 ? ?char character;
 ? ?virtual bool operator==(const D& a) const
 ? ?{
 ? ? ? ?return name == a.name && number == a.number && character == a.character;
 ? ?}
 ? ?// ...
};

B b = ...
D d = ...
b == d; ? ?// compares name and number, ignores d's character
d == b; ? ?// error: no == defined
D d2;
d == d2; ? // compares name, number, and character
B& b2 = d2;
b2 == d; ? // compares name and number, ignores d2's and d's character

Of course there are ways of making == work in a hierarchy, but the naive approaches do not scale

当然有办法让相等比较运算符在继承体系中动作,但是简单的方法不行。

Note(注意)

This rule applies to all the usual comparison operators: !=, <, <=, >, and >=.

本规则适用于所有的常见比较运算符:!=, <, <=, >, 和 >=。

Enforcement(实施建议)

  • Flag a virtual operator==(); same for other comparison operators: !=, <, <=, >, and >=.
  • 提示被定义为虚函数的相等比较运算符;其他比较运算符也一样:!=, <, <=, >, 和 >=。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c87-beware-of--on-base-classes


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

最近发表
标签列表