A simple example of C ++ overload Operators
We can redefine or reload most of the built-in operators in C ++. In this way, you can use custom operators.
The overloaded operator is a function with a special name. The function name is composed of the operator keyword and the operator symbol to be reloaded. Like other functions, the overload operator has a return type and a parameter list.
Box operator + (const Box &);
The Declaration addition operator is used to add two Box objects and return the final Box object. Most overload operators can be defined as common non-member functions or class member functions. If we define the above function as a non-member function of the class, we need to pass two parameters for each operation, as shown below:
Box operator + (const Box &, const Box &);
The following example uses a member function to demonstrate the concept of operator overloading. As follows:
# Include <iostream>
Using namespace std;
Class Person {
Public:
Person (int num): age (num ){}
/* Class member functions */
Int operator + (const Person & temp ){
Return (this-> age + temp. age );
}
Int age;
};
/* Non-class member functions */
Int operator-(const Person & a, const Person & B ){
Return (a. age-b.age );
}
Int main ()
{
Person John (20), Tom (18 );
Cout <John + Tom <endl;
Cout <John-Tom <endl;
Return 0;
}
--------------------------------------------------------------------------------
Reload operators/non-overload Operators
The following is a list of operators that can be reloaded:
Category |
Symbol |
Binary Arithmetic Operators |
+ (Plus),-(minus), * (multiplication),/(Division), % (Modulo) |
Relational operators |
= (Equal ),! = (Not equal to), <(less than),> (greater than>, <= (less than or equal to), >=( greater than or equal) |
Logical operators |
(Logical or), & (logical and ),! (Non-logical) |
Single Object Operator |
+ (Positive),-(negative), * (pointer), & (obtain address) |
Auto-incrementing auto-subtraction Operator |
++ (Auto increment), -- (Auto increment) |
Bitwise operators |
(By bit or), & (by bit and ),~ (Bitwise inversion), ^ (bitwise XOR), <<< (left shift), >>( right shift) |
Value assignment operator |
=, + =,-=, * =,/=, % =, & =, ^ =, <=,> = |
Space Application and release |
New, delete, new [], delete [] |
Other operators |
() (Function call),-> (member access), (comma), (subscript) |
The following is a list of operators that cannot be overloaded:
.: Member access operator
. *,-> *: Member pointer access operator
: Domain operator
Sizeof: length Operator
? : Conditional Operators
#: Preprocessing symbol
This article permanently updates link: https://www.bkjia.com/Linux/2018-02/151083.htm