on a board level, operators in c++ can be classified into two type: unary operators and binary operators.
unary operators
operators that function on a single operand are called unary operators.
type of unary operators
| operator | name |
|---|---|
| ++ | increment |
| -- | decrement |
| * | pointer dereference |
| -> | member selection |
| ! | logical not |
| & | Address-of |
| ~ | one's complement |
| + | unary plus |
| - | unary negation |
| conversion operators | conversion into other types |
programming a ++/-- operator
prefix increment operator (++):
1 | Date & operator ++() |
postfix increment operator (++)
1 | Date operator ++ (int) |
A calendar class that handles day, month, and year, and allows incrementing and decrementing days. demolist12_1
1 |
|
the output
1 |
prefix increment operators as demonstrated in this sample need to return a reference to the instance after the increment operation.
To support postfix increment and decrement:
1 | Date operator ++(int) |
The syntax using postfix:
1 | mysteryDay++; |
comparison:
Better using prefix increment of decrement for avoiding the creation of temporary copy.
programming conversation operators
if you use demolist12_1 and insert the following line in main():
1 | cout << holiday; //error in absence of conversion operator |
The code would result in the following compile failure:
1 | error: binary '<<': no operator found which takes a right-hand operand of type 'Date'. |
This error essentially indicates that cout doesn't know how to interpret an instance of Date as class Date. Adding an operator to get cout work with an instance of type Date.
e.g. Implementing conversion operator const char* for class Date demolist12_2·
1 |
|
As shown in line 16 and 23, the benefit of implementing operator const char* is visible in line inmain. Now an instance of class Date can directly be used in a cout statement, taking advantage of the fact that cout understands const char*.
programming dereference operator (*) and member selection operator (->)
This lesson takes a brief look at how overloading operators helps in making smart pointers work.
e.g. using smart pointer unique_ptr to manage a dynamically allocated instance of class Date.demolist12_3
1 |
|
Line 22 where I declare a smart pointer to type int. this line shows template initialization syntax for smart pointer class unique_ptr. Similarly, line 27 declare a smart pointer to an instance of Date. The pointer class std::unique_ptr that is smart because it implements operator(*) and operator(->).