|
Bit and Logical Operators
In this section, we will deal with how to overload bit manipulation operators such as &, | and ~, as well as the
logical operators &&, || and !. We have
already seen how to overload some other bit manipulation operators (<< and >>) in the Bitshift/Extraction
operators section. In here, we will deal with overloading the others.
The first thing to determine is how C++ classifies these operators as:
Operator Name Type
-------- -------------------- ---------
& Bitwise AND operator Binary
| Bitwise OR operator Binary
~ Ones complement Unary
&& Logical AND operator Binary
|| Logical OR operator Binary
! Logical NOT operator Unary
What this means is that the &, |, && and || operators work with two arguments and the ~ and ! operators
only work with one argument.
Thus, we can use some other overloaded functions that we studied previously as examples. Matter of fact, if you look at
the Unary Operators section, we already discussed how to overload the ~ and ! operators in that
section.
We also looked at how to overload the & operator there (albeit in the context of an address-of operator, which is unary).
To overload the bitwise & and | operators, as well as the logical && and || operators, we look at other binary
operators that we overloaded previously. The code that
we developed in the Arithmetic Operators and Arithmetic with
Globals section are examples of overloading binary operators.
Thus, if you have been reading all the examples in this tutorial from the beginning, overloading these operators ought to
be child's play for you now.
As an example, we will overload the & operator to concatenate two std::string objects. While this operator is not used
for that purpose by any C++ programmers, Visual Basic programmers are quite used to concatenating strings this way. Hence,
the following code may make seasoned C++ programmers recoil with horror, but VB programmers who are moving to C++,
will treat you like a God.
#include <iostream>
#include <string>
using namespace std;
string operator&(const string& s1, const string& s2) {
string sResult = s1 + s2;
return sResult;
}
int main(void) {
string str1 = "foo";
string str2 = "bar";
string str3 = str1 & str2;
cout << str3 << endl;
return 0;
}
You are invited to verify that the above code actually concatenates the strings as advertised.
Exercises
1. Visual Basic programmers are used to seeing the & operator used for concatenating strings to other objects as well.
Overload the & operator to work between std::string and integer, long, double, float etc. You could perhaps use functions
such as atoi(), atol(), atof() etc. to do the conversions, or use the C++ strstream object.
Remember -- This is ONLY A LEARNING EXERCISE. Do NOT ever advertise that you did this in the real world.
While it may earn you the gratitude of the VB crowd, the C++ programmers will come looking for your head.
|
|