C++核心準則C.160:定義運算符主要是為了模仿習慣用法

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 operands.?Binary operators should treat their operands equivalently.
非成員運算符應(yīng)該要么是友元函數(shù),要么和操作對象定義在一起。二進制運算符應(yīng)該同等對待操作對象。
Enforcement(實施建議)
Possibly impossible.
可能無法做到。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c160-define-operators-primarily-to-mimic-conventional-usage
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
評論
圖片
表情
