Overloading unary operators
Unlike the operators you’ve seen so far, the positive (+), negative (-) and logical not (!) operators all are unary operators, which means they only operate on one operand. Because none of these operators change their operands, we will be implementing them as friend functions. All three operands are implemented in an identical manner.
Let’s take a look at how we’d implement operator- on the Cents class we used in a previous example:
07 | Cents( int nCents) { m_nCents = nCents; } |
10 | friend Cents operator-( const Cents &cCents); |
14 | Cents operator-( const Cents &cCents) |
16 | return Cents(-cCents.m_nCents); |
This should be extremely straightforward. Our overloaded negative operator (-) takes one parameter of type Cents, and returns a value of type Cents.
Here’s another example. The ! operator is often used as a shorthand method to test if something is set to the value zero. For example, the following example would only execute if nX were zero:
Similarly, we can overload the ! operator to work similarly for a user-defined class:
04 | double m_dX, m_dY, m_dZ; |
07 | Point( double dX=0.0, double dY=0.0, double dZ=0.0) |
15 | friend Point operator- ( const Point &cPoint); |
18 | friend bool operator! ( const Point &cPoint); |
20 | double GetX() { return m_dX; } |
21 | double GetY() { return m_dY; } |
22 | double GetZ() { return m_dZ; } |
26 | Point operator- ( const Point &cPoint) |
28 | return Point(-cPoint.m_dX, -cPoint.m_dY, -cPoint.m_dZ); |
32 | bool operator! ( const Point &cPoint) |
34 | return (cPoint.m_dX == 0.0 && |
In this case, if our point has coordinates (0.0, 0.0, 0.0), the logical not operator will return true. Otherwise, it will return false. Thus, we can say:
4 | cout << "cPoint was set at the origin." << endl; |
6 | cout << "cPoint was not set at the origin." << endl; |
which produces the result:
cPoint was set at the origin.
No comments:
Post a Comment