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

  • 相关阅读:
    javascript基础全等号运算符
    javascript 使用ScriptX实现打印
    跨服务器与本地服务器不同数据库的SQL操作语句
    ASP.NET网络上实现单点登录
    FGMap API 帮助文档
    基于ArcEngine写的GoogleMap地图切割程序
    基于SuperMap Objects写的GoogleMap地图切割程序(三)
    使用SuperSocket开发联网斗地主(四):出牌
    JAVA创建对象方法
    Mysql 外键约束
  • 原文地址:https://www.cnblogs.com/scw2901/p/4228971.html
Copyright © 2011-2022 走看看