C.160:定义运算符主要是为了模仿习惯用法
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
Nonmember operators should be either friends or defined in the same namespace as their operands. Binary 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
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!