C++核心准则C.160:定义运算符主要是为了模仿习惯用法

共 1056字,需浏览 3分钟

 ·

2020-02-26 23:22

2359e84034103b0c41583b7c5ed07eab.webp

C.160: Define operators primarily to mimic conventional usage

C.160:定义运算符主要是为了模仿习惯用法


Reason(原因)

Minimize surprises.

让程序看起来更自然。


Example(示例)

class X {
public:
// ...
X& operator=(const X&); // member function defining assignment
friend bool operator==(const X&, const X&); // == needs access to representation
// after a = b we have a == b
// ...
};

Here, the conventional semantics is maintained: Copies compare equal.

这里,赋值,相等比较的习惯语义得以保持。


Example, bad(反面示例)

X operator+(X a, X b) { return a.v - b.v; }   // bad: makes + subtract

Note(注意)

Nonmember operators should be either friends or defined in the same namespace as their operandsBinary operators should treat their operands equivalently.

非成员运算符应该要么是友元函数,要么和操作对象定义在一起。二进制运算符应该同等对待操作对象。


Enforcement(实施建议)

Possibly impossible.

可能无法做到。


原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c160-define-operators-primarily-to-mimic-conventional-usage




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

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

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

浏览 46
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

分享
举报