+ 8
Operator overloading
Can anyone clearly explains operator overloading with an example?
9 Réponses
+ 7
@Mario, To add the age of two persons we can simply use '+'? then why we should operator overload??. My question may be stupid but still I wanna know.
+ 6
#Daohacker , Give one.
+ 5
@Mario Laurisch making the sum of 2 people be the sum of their ages seems a bad example though. I guess I will provide an example after all...
+ 5
Ok, C++ isn't a language I know yet, so it took me some time, but here it is:
#include <iostream>
using namespace std;
class Square {
private:
int side;
public:
void SetSide(int s) {
this->side = s;
}
int Perimeter() {
return side * 4;
}
Square operator+(const Square& b) {
Square c;
c.SetSide(this->side + b.side);
return c;
}
};
int main() {
Square sq1, sq2;
sq1.SetSide(3);
sq2.SetSide(5);
Square sq3 = sq1 + sq2;
cout << sq3.Perimeter() << endl;
return 0;
}
With this example, you can easily create a new square which has perimeter equal to the sum of 2 other squares' perimeter.
+ 4
Operator Overloading is used to redefine the meaning of operators when used on specific data types. I could make an example, but i'm lazy... I'm just replying because nobody did yet, I'm sure some kind soul will provide you one.
+ 3
you use it to define how your self created objects behave when used with operators. let's say you have a class defining a person. a person has an age. now you have two objects of type person and want to get the sum of their ages. that's where you'd overload the + operator.
an example is within the course.
you could also define that the + operator returns the product of two objects.
+ 3
well, now I'm interested too. the way I explained it is the way I understood the example in the course.
so there's more to it than just defining operations on object's attributes?
0
Operator overloading is very similar to function overloading. Operator overloading is where you redefine an operator so it behaves in a certain way for a user defined type like a class.
a quick example in c++:
class Point
{
public:
float x;
float y;
Point operator+(const Point& secondPoint);
};
Point Point::operator+(const Point& secondPoint)
{
Point newPoint;
newPoint.x = x + secondPoint.x;
newPoint.y = y + secondPoint.y;
return newPoint; // return the new point.
}
then later you could declare 2 point objects, assign them values and add them together with the + operator
Point point1;
point1.x = 1.0f;
point1.y = 2.0f;
Point point2;
point2.x = 5.0f;
point2.y = 6.0f;
Point point3;
point3 = point1 + point2;
0
Another example:
https://www.tutorialspoint.com/cplusplus/cpp_overloading.htm
I hope it's helpful.