C++ Unary Operators Overloading
C++ Overloaded Operators and Overloaded Functions
A unary operator operates on only one operand. The following are examples of unary operators:
- The increment operator (++) and the decrement operator (--)
- The unary minus operator, i.e., the negative sign (-)
- The logical NOT operator (!)
Unary operators usually appear to the left of the object they operate on, such as !obj, -obj, and ++obj, but sometimes they can also be suffixes, such as obj++ or obj--.
The following example demonstrates how to overload the unary minus operator (-).
Example
#include
<
iostream
using
namespace
std;
class
Distance
{
private
:
int
feet
;
// 0 to infinity
int
inches
;
// 0 to 12
public
:
// required constructor
Distance
(
)
{
feet
=
0
;
inches
=
0
;
}
Distance
(
int
f
,
int
i
)
{
feet
=
f
;
inches
=
i
;
}
// method to display distance
void
displayDistance
(
)
{
cout
<<
"
F:
"
<<
feet
<<
"
I:
"
<<
inches
<<
endl
;
}
// overload the negation operator (-)
Distance
operator
(
)
{
feet
= -
feet
;
inches
= -
inches
;
return
Distance
(
feet
,
inches
)
;
}
}
;
int
main
(
)
{
Distance
D1
(
11
,
10
)
,
D2
(
5
,
11
)
; -
D1
;
// take the opposite value
D1
.
displayDistance
(
)
;
// distance D1
D2
;
// take the opposite value
D2
.
displayDistance
(
)
;
// distance D2
return
0
;
}
When the code above is compiled and executed, it produces the following result:
F: -11 I:-10
F: 5 I:-11
I hope the example above helps you better understand the concept of unary operator overloading. Similarly, you can try overloading the logical NOT operator (!).