In Object Oriented Programming, the idea is to be as realistic as possible. In native programming languages, only types like integers, floating numbers, and boolean values are included in the default program. What if you would want to build your own type? let's say, a math vector?
In fact, for that, you start by creating a
class, let's call it MathVector. This class should, however, have 3 elements for the 3 components in space. Let's call them x y z, and put them in the class too.
class MathVector
{
public: //leave this public part for later times. For now, just include it at the beginning of your class
double x;
double y;
double z;
}
Now we have a new type called MathVector. Whenever we define that type, we get an x, y and z!!! Let's use that in a small program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
int main()
{
MathVector myFirstVector; //created a vector with 3 components
MathVector mySecondVector; //created another vector with 3 components
//now let's give the vectors some values
myFirstVector.x = 5;
myFirstVector.y = 3;
myFirstVector.z = 7;
mySecondVector.x = 2;
mySecondVector.y = 1;
mySecondVector.z = 6;
//now we have 2 vectors. How about we add those 2 vectors and assign them to a third vector?
MathVector myThirdVector;
myThirdVector = myFirstVector + mySecondVector;
//ooooops... this will not compile... why?
}
|
Read the code. Now this last line won't compile. Why? because you simply didn't tell your compiler what adding vectors mean. What the compiler sees is a container with 3 double values. It doesn't know what those values are. That's why you have to define the
addition operator,
operator+
, to tell your compiler how it's supposed to add those vectors.
Let's edit that class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class MathVector
{
public:
double x;
double y;
double z;
friend MathVector operator+(const MathVector& left_hand_side, const MathVector& right_hand_side)
{
MathVector returnVal;
returnVal.x = left_hand_side.x + right_hand_side.x;
returnVal.y = left_hand_side.y + right_hand_side.y;
returnVal.z = left_hand_side.z + right_hand_side.z;
//here you told your compiler how addition has to be done. Now it would compile
return returnVal;
}
}
|
Now the main code with addition should compile. Because you informed your compiler that adding vectors mean adding each component to the corresponding one.
I'm not so sure whether the code is 100% syntactically correct. I just wanted to explain operators. So good luck implementing it :-)
Hope this helps!
Cheers.