Tuesday, November 12, 2024
HomeComputer programmingC++: Operator Overloading (Even a Little More Complex)

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

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)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

LATEST REVIEWS

Recent Comments

error: Content is protected !!