C++: Operator Overloading (even a little more complex)

Contributor Icon Contributed by William_Wilson Date Icon February 27, 2006  
Tag Icon Tagged: Computer programming

How to Overload the operators: +=, -=, *=, /=, %=


Very similar to overloading the +,-,* operators within a class, as they all take a single parameter as such:

As with all the other Person will be the custom class.
Perhaps these operations combine the friends of 2 people to the friends of one of the persons.

+= Operator:

Person& operator+=(const Person& p1){
this->friends = this->friends + p1.friends;
return *this;
}

-= Operator:

Person& operator-=(const Person& p1){
this->friends = this->friends - p1.friends;
return *this;
}

*= Operator:

Person& operator*=(const Person& p1){
this->friends = this->friends * p1.friends;
return *this;
}

/= Operator:

Person& operator/=(const Person& p1){
this->friends = this->friends / p1.friends;
return *this;
}

%= Operator:

Person& operator%=(const Person& p1){
this->friends = this->friends % p1.friends;
return *this;
}

*As you can see they are all very similar, add in most cases must be defined within the case they are defining operations for. Not that i can see presidence for ever doing anything else.

*Also note that although there is no recipe on pointers, p1 uses the . to refer to it’s category friends, as it is passed by reference (NOTE the &) while the implied Person object designated by this must use the -> pointer to access it’s version. The difference being, that p1 represents the Person object and can access directly, while this merely points to a person object (eg knows where the object is).

Questions/Comments: william_a_wilson@hotmail.com
-William. ยง (marvin_gohan)

Previous recipe | Next recipe |
 
blog comments powered by Disqus