前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.167:为具有约定俗成​语义的操作使用运算符

C++核心准则C.167:为具有约定俗成​语义的操作使用运算符

作者头像
面向对象思考
发布2020-03-25 16:59:40
3430
发布2020-03-25 16:59:40
举报

C.167: Use an operator for an operation with its conventional meaning

C.167:为具有约定俗成语义的操作使用运算符

Reason(原因)

Readability. Convention. Reusability. Support for generic code。

可读性。遵守惯例。可复用性。支持泛化代码。

Example(示例)

void cout_my_class(const My_class& c) // confusing, not conventional,not generic
{
    std::cout << /* class members here */;
}

std::ostream& operator<<(std::ostream& os, const my_class& c) // OK
{
    return os << /* class members here */;
}

By itself, cout_my_class would be OK, but it is not usable/composable with code that rely on the << convention for output:

如果只考虑自己的话,cout_my_class还不错,但是它无法在通过<<运算符输出的代码中使用(或者和这样的代码一起使用)。

My_class var { /* ... */ };
// ...
cout << "var = " << var << '\n';
Note(注意)

There are strong and vigorous conventions for the meaning most operators, such as

很多操作符具有强烈而且活跃的约定含义,例如:

  • comparisons (==, !=, <, <=, >, and >=),
  • 比较运算符
  • arithmetic operations (+, -, *, /, and %)
  • 数学运算符
  • access operations (., ->, unary *, and [])
  • 访问运算符
  • assignment (=)
  • 赋值运算符

Don't define those unconventionally and don't invent your own names for them.

不要违反惯例定义这些运算符,也不要为它们发明新名称。

Enforcement(实施建议)

Tricky. Requires semantic insight.

不容易。需要语义方面的深入理解。

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c167-use-an-operator-for-an-operation-with-its-conventional-meaning


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

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

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C.167: Use an operator for an operation with its conventional meaning
  • Reason(原因)
    • Note(注意)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档