Interfacing with C plus plus-programing communication with microcontrolers (K. Bentley, 2006)
.pdf12.1 Introduction
Some of the programs written in this book can be improved to require less memory when executing, and also operate faster by using pass by reference and return by reference mechanisms. They can also be changed to take advantage of simpler statements by using operator overloading and gain access to private member data through friend functions.
In this chapter, we will develop a data acquisition program to demonstrate how operator overloading can be used to write elegant programs that have the advantages outlined above. During data acquisition, signals are converted to data using a device such as an analog-to-digital converter. The data is then directly processed or written to a data file on a mass storage device such as a hard disk, or in some cases, sent to a standard output device such as a screen or printer.
12.2 Operator Overloading
When an operator is overloaded, the action carried out by the operator depends on the arguments the operator is associated with. For example, the results will be different if the division operator ( / ) is used in the following two contexts. One operation produces integer division and the other floating-point division:
5/2; // the result is 2 5.0/2.0; // the result is 2.5
Similarly, the double left arrow operator behaves in two different ways in the following two cases:
int y = |
200; |
output. |
|
cout |
<< |
y; // 200 is sent to the standard |
|
y << |
1; |
// Shifts bits of y to left by |
1 bit-position. |
The action of an operator depends on the type of object it is used with. In the expression cout << y, cout is a class object of type ostream and y is an object of type int. The << operator takes appropriate action to print the value of y on the screen. However, both operands are of type integer in y << 1, and the action taken by the operator is to shift bits of y by 1 bit-position to the left.
The operators shown in Table 12-1 cannot be overloaded.
Table 12-1 Operators that cannot be overloaded.
. ?: :: .* sizeof