Unary and binary operator overloading in C++
This article is mainly about "unary and binary operator overloading in C++". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "unary and binary operator overloading in C++".
Operator overloading is to redefine an existing operator and give it another function to adapt it to different data types.
The essence of operator overloading: function overloading keyword: operator
Unary operator overloading
The unary operator is to operate on a number
When unary operator overloading uses member functions for overloading, there is no need to pass parameters to (). There is a hidden * this in ()
Overloading of minus operator
Define a Coordinate coordinate class that overloads the minus operator through member functions and friend functions, respectively.
Overload the minus operator through member functions:
# include
Using namespace std
/ * *
Unary operator overloading
Request:
Define a Coordinate coordinate class
Member functions: construction, getX, getY, data member: mSecretiX _ mcm _ iY
1. Negative operator overloading (member function, friend function)
2. + operator overloading (pre-+, post-+)
* * /
Class Coordinate
{
Coordinate (int x pencil int y)
/ / overload symbolic operators through member functions
Coordinate & operator- (); / / it is itself that asks him to return, so that he can operate on the minus operator again, so the return value is written as Coordinate &
Int getX ()
Int getY ()
Private:
Int m_iX
Int m_iY
}
Coordinate::Coordinate (int x pencil int y)
{
M_iX = x
M_iY = y
}
Int Coordinate::getX ()
{
Return m_iX
}
Int Coordinate::getY ()
{
Return m_iY
}
/ / member function to realize negative sign operator overloading
Coordinate & Coordinate::operator- ()
{
This- > m_iX =-(this- > m_iX); / / m_iX =-m_iX
This- > m_iY =-(this- > m_iY)
Return * this;// returns an object
}
Int main ()
{
Coordinate coor1 (1pr 3)
Cout