PDA

View Full Version : Could someone explain operator overloading to me?


bennycs
06-18-2003, 01:39 AM
Hey, new to the forum! Well I was wondering if someone could clarify operator overloading for me. If I have a class with this operator overloading function

int operator+(int n, int n2)
{
int sum = n + n2;
return sum;
}
is this correct? i don't really understand the concept and my teacher and book are really vague. thanks for any advice.

stoodder
06-18-2003, 02:07 AM
it all looks good except for the + after operator, it might work but im not really sure, so just to be safe id go without the pluss lol.

void operator(int n,int n2)
{
int sum = n + n2;
return sum;
}


also the best way(for me) to out putan answer or some tesext is to do this:

void mail(int n,int n2) {
std::cout<<n + n2;
}

int main() {
mail(4,2);
system("pause");
}



you might wanna usevoid also, cause for sme reaso i got errors with using int mail()

djdante97
06-21-2003, 08:23 PM
You use operator overloading to be able to use the common operators with your own classes. If you had a Rectangle object that computes it's own area and you wanted to add two of these areas, you could simply make a function that takes in two Rectangle objects and returns an int. OR you overload the "+" operator similar to what you have done. Here's an example of the difference between the two methods:
method 1: no overloading
totalArea = sumAreas(rect1, rect1);

method 2: operator overloading
totalArea = rect1 + rect2;

So to write this function to overload the + operator for the Rectangle class, you need to add something like the following to the class:

int Rectangle::operator+ (const Rectangle& r) {
return (this.area + r.area);
}