An operator is just a function that you can call with operator syntax. So, remember that to call a method, you would go:
object.Plus(1);
With operators, you can use operator syntax:
object + 1;
Now, what your version of the + operator does is completely up to you. (I don't recommend this, but if you wanted to be sneaky, you could overload the + operator to do subtraction and the - operator to do addition!)
So, when overloading operators, we can do it two ways:
1. - Have them as MEMBERS of a class - methods
2. - Just have them as regular operator functions that belong to no class and can be called by anyone.
There are differences, between the two, but we'll take a look at each one.
First off, let's have a look at operator overloading where you do NOT make it a class method.
An example would be:
- Object operator + (const Object &leftOperand, const Object &rightOperand) const
- {
- //Suppose that Class Object has two data members: x and y
- Object temp;
- temp.x = leftOperand.x + rightOperand.x;
- temp.y = leftOperand.y + rightOperand.y;
- return temp;
- }
(Line numbers are for reference only.)
Now, what does this do? It overloads the + operator to use it with variables (objects) of class Object. It performs addition, by adding the x and y data members of each operand together and stores the results into a new Object variable which it then returns.
So, later on in main() you could do this:
Object left;
Object right;
Object result = left + right;
Now, notice that the Object 'left' will go into leftOperand and 'right' will go into the rightOperand parameter. That's how it is with operators that are NOT methods of a class.
If you decided to overload the + operator for a class, then it would look something like this:
- class Object
- {
- public:
- Object operator + (const Object &rightOperand) const;
- //More code here
- };
- Object Object::operator + (const Object &rightOperand) const
- {
- Object temp;
- temp.x = x + rightOperand.x;
- temp.y = y + rightOperand.y;
- return temp;
- }
Now, note that we only need a parameter for the right operand. Where's the left operand? The left operand is the object used to call the + operator.
So, if we do this:
objThree = objOne + objTwo;
You can imagine the statement as looking like this:
objThree = objOne.+(objTwo);
objTwo is passed in as the rightOperand and the + operator is using objOne's x and y data members and adding them to rightOperand's corresponding members.
The result is then stored in Object temp, which is then returned.
(I'll probably continue this in another blog post.)
Joe
No comments:
Post a Comment