前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.87:小心基类的相等运算符

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

作者头像
面向对象思考
发布2020-03-25 16:27:09
3730
发布2020-03-25 16:27:09
举报
文章被收录于专栏:C++核心准则原文翻译

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(反面示例)

代码语言:javascript
复制
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的相等比较运算符的第二个操作数接受类型转换,但是第一个不行。

代码语言:javascript
复制
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


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

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-01-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档