zoukankan      html  css  js  c++  java
  • c++运算符重载如何决定作为成员函数还是非成员函数

    The Decision between Member and Non-member

    The binary operators = (assignment), [] (array subscription), -> (member access), as well as the n-ary () (function call) operator, must always be implemented as member functions, because the syntax of the language requires them to.

    Other operators can be implemented either as members or as non-members. Some of them, however, usually have to be implemented as non-member functions, because their left operand cannot be modified by you. The most prominent of these are the input and output operators <<and >>, whose left operands are stream classes from the standard library which you cannot change.

    For all operators where you have to choose to either implement them as a member function or a non-member function, use the following rules of thumb to decide:

    1. If it is a unary operator, implement it as a member function.
    2. If a binary operator treats both operands equally (it leaves them unchanged), implement this operator as a non-member function.
    3. If a binary operator does not treat both of its operands equally (usually it will change its left operand), it might be useful to make it a member function of its left operand’s type, if it has to access the operand's private parts.

    Of course, as with all rules of thumb, there are exceptions. If you have a type

    enum Month {Jan, Feb, ..., Nov, Dec}
    

    and you want to overload the increment and decrement operators for it, you cannot do this as a member functions, since in C++, enum types cannot have member functions. So you have to overload it as a free function. And operator<() for a class template nested within a class template is much easier to write and read when done as a member function inline in the class definition. But these are indeed rare exceptions.

    (However, if you make an exception, do not forget the issue of const-ness for the operand that, for member functions, becomes the implicit this argument. If the operator as a non-member function would take its left-most argument as a const reference, the same operator as a member function needs to have a const at the end to make *this a const reference.)

    ----------------------------------------------------

    原文:http://stackoverflow.com/questions/4421706/operator-overloading/4421729#4421729

  • 相关阅读:
    浅谈Java中的hashcode方法
    framework
    js 去掉字符串最后一个逗号:笑死我了
    .net MVC4.0项目发布到阿里云虚拟主机中遇到的问题。
    Bootstrap学习第二天轮播插件
    Bootstrap学习第一天
    图灵机器人api的使用方法含微信版本和网页版
    sql.表值类型
    asp.net中的日志添加和未处理异常的记录
    C# 结构类型与类的区别
  • 原文地址:https://www.cnblogs.com/scw2901/p/4228971.html
Copyright © 2011-2022 走看看