c++运算符重载-如何决定作为成员函数还是非成员函数
2015-01-16 15:52
351 查看
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:
If it is a unary operator, implement it as a member function.
If a binary operator treats both operands equally (it leaves them unchanged), implement this operator as a non-member function.
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
thisargument. If the operator as a non-member function would take its left-most argument as a
constreference, the same operator as a member function needs to have a
constat the end to make
*thisa
constreference.)
----------------------------------------------------
原文:http://stackoverflow.com/questions/4421706/operator-overloading/4421729#4421729
相关文章推荐
- 如何让C++类的成员函数作为回调函数
- 如何使类的成员函数作为回调函数
- 在类中const成员函数和非const成员函数可以作为重载成员函数同时存在
- C++运算符重载函数作为类成员函数和友元函数
- c++运算符重载,做为成员函数
- C++运算符重载函数作为类成员函数和友元函数
- 如何实现类的成员函数作为回调函数
- 如何让类的成员函数作为回调函数
- 如何使类的成员函数作为回调函数
- 如何使 类的成员函数作为回调函数
- 如何实现类的成员函数作为回调函数
- 如何将一个函数声明为两个类的友元或将该函数作为一个类的成员,另一个类的友元
- C++运算符重载 成员函数与友元函数
- 如何使 类的成员函数作为回调函数
- 如何让类的成员函数作为回调函数
- 如何实现类的成员函数作为回调函数
- 如何让C++类的成员函数作为回调函数
- C++运算符重载(成员函数以及友元函数实现)
- C++运算符重载(成员函数方式)
- C++运算符重载(成员函数以及友元函数实现)