C++核心准则C.87:小心基类的相等运算符

共 1394字,需浏览 3分钟

 ·

2020-01-22 23:23

f47ee4d46a23df02b250a16f3bbbb9b3.webp

紫黄晶

35b3a296268e1b7cb8b35514cd804457.webp
1439c1d90e4fc13ae8b8afc1b68b3d88.webp

C.87: Beware of == on base classes

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


1439c1d90e4fc13ae8b8afc1b68b3d88.webp
35b3a296268e1b7cb8b35514cd804457.webp


32be7b093d20b8e3f119ecc410466559.webp965126e2e61d225f61a944e7e15219c9.webpReason(原因)965126e2e61d225f61a944e7e15219c9.webp

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

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


32be7b093d20b8e3f119ecc410466559.webp965126e2e61d225f61a944e7e15219c9.webpExample, bad(反面示例)965126e2e61d225f61a944e7e15219c9.webp
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

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


32be7b093d20b8e3f119ecc410466559.webp965126e2e61d225f61a944e7e15219c9.webpNote(注意)965126e2e61d225f61a944e7e15219c9.webp

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

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


32be7b093d20b8e3f119ecc410466559.webp965126e2e61d225f61a944e7e15219c9.webpEnforcement(实施建议)965126e2e61d225f61a944e7e15219c9.webp
  • Flag a virtual operator==(); same for other comparison operators: !=, <, <=, >, and >=.

  • 提示被定义为虚函数的相等比较运算符;其他比较运算符也一样:!=, <, <=, >, 和 >=。

32be7b093d20b8e3f119ecc410466559.webp965126e2e61d225f61a944e7e15219c9.webp原文链接965126e2e61d225f61a944e7e15219c9.webp

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




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

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

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

浏览 7
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报