Operation symbol overloading in C + + is implemented through member functions that are global functions, in order to achieve access to member data, the global function is typically declared as a friend. Overloaded function names using the operator keyword, such as operator op (), OP can be a common + 、-、 *,/, or other operation number, or you can customize the conversion function such as: operator int (), which defines how the object is converted to int.
- Overloaded functions are called in such a way that A+b,a is a class object, and if you implement A + overload, you call a.operator+ (b), where the + operator acts on the left object, for example:
std::string""; str. operator+ = ("World"); // quite with str + = "World";
- Because the operator acts on the left object or variable, use needs to be aware of the order of the left and right sides, for example:
classfoo{ Public: Foo (intData=0): m_data (data) {} Foo&operator+(inta) {m_data+=A; return* This; } Friend Std::ostream&operator<< (std::ostream& OS,Constfoo&f) {returnOS <<F.m_data; }Private: intm_data;};
At this point define the object, statement Foo A; A + 1; normal execution, 1 + A; Cannot compile because the + operation definition of the constant 1 cannot be found, and the friend function is defined:
operator+ (int A, foo& f) { return f + A;}
Statement 1 + A; The overload resolution of C + + is interpreted as operator+ (1, a) and can be passed normally.
C + + operator overloading (Boolan)