C++: Operator Overloading (Even a Little More Complex)

Posted February 27, 2006 by William_Wilson in Computer programming

Use the instructions in this tech recipe to Overload the operators: +=, -=, *=, /=, %=.


These steps are very similar to overloading the +,-,* operators within a class, as they all take a single parameter as such.

As with all the others, Person will be the custom class.
Perhaps these operations combine the friends of two people with 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, and in most cases, must be defined within the case for which they are defining operations. I cannot see a precedence for ever doing anything else.

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

Questions/Comments: [email protected]
-William. ยง (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.