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.

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

Enforcement(实施建议)

Possibly impossible.

可能无法做到。

原文链接:

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


觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

原创文章 414 获赞 724 访问量 35万+

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/105665568