Operator function: operator
Operator Overloading:
A. Become a member function
B. namespace functions (youyuan functions)
The following operators cannot be overloaded :::,.,.*,? :
Operators that must be reloaded as member functions: [], (),->, =
Requirements:
A. New operators cannot be introduced.
B. Do not change the number of elements, priority, and combination.
Definition Syntax:
Binary Functions
Value Type operatoe ◎ (type name-form parameter name) function body // member function
Value Type operatoe ◎ (type name and type name) function body // global function
Unary Functions
Value Type operatoe ◎ () function body // member function
Value Type operatoe ◎ (type name-form parameter name) function body // global function
Example program:
# Include <iostream>
Using namespace std;
Class com {
Private:
Int real;
Int img;
Public:
Com (int real = 0, int img = 0 ){
This-> real = real;
This-> img = img;
}
Void com_add (com & x, com & y, com & z ){
Z. real = x. real + y. real;
Z. img = x. img + y. img;
}
Com operator + (com x ){
Return com (this-> real + x. real, this-> img + x. img );
}
/*
Com operator + (com & x ){
Return com (this-> real + x. real, this-> img + x. img );
}
*/
/*
// Warning c00002: returning address of local variable or temporary
Com & operator + (com & x ){
Return com (this-> real + x. real, this-> img + x. img );
}
*/
Com operator + (int x ){
Return com (this-> real + x, this-> img );
}
Friend com operator + (int x, com y );
Void show (){
Cout <real <"," }
};
Com operator + (int x, com y ){
Return com (x + y. real, y. img );
}
Int main ()
{
Com a, B (1, 2), c (2, 3 );
A = B + c;
A. show ();
A.com _ add (B, c, );
A. show ();
A = B + 3;
A. show ();
A = 3 + c;
A. show ();
}
Note: com & operator + (com & x)
Overload operators in class member functions are not allowed to return references, and the "return local variable address" Warning is displayed.
However, the void com_add (com & x, com & y, com & z) function is supported.