What is an overloaded operator in c++?
- by Jeff
I realize this is a basic question but I have searched online, been to cplusplus.com, read through my book, and I can't seem to grasp the concept of overloaded operators. A specific example from cplusplus.com is:
// vectors: overloading operators example
#include <iostream>
using namespace std;
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};
CVector::CVector (int a, int b) {
x = a;
y = b;
}
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}
int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}
from http://www.cplusplus.com/doc/tutorial/classes2/ but reading through it I'm still not understanding them at all. I just need a basic example of the point of the overloaded operator (which I assume is the "CVector CVector::operator+ (CVector param)").
There's also this example from wikipedia:
Time operator+(const Time& lhs, const Time& rhs)
{
Time temp = lhs;
temp.seconds += rhs.seconds;
if (temp.seconds >= 60)
{
temp.seconds -= 60;
temp.minutes++;
}
temp.minutes += rhs.minutes;
if (temp.minutes >= 60)
{
temp.minutes -= 60;
temp.hours++;
}
temp.hours += rhs.hours;
return temp;
}
from "http://en.wikipedia.org/wiki/Operator_overloading"
The current assignment I'm working on I need to overload a ++ and a -- operator.
Thanks in advance for the information and sorry about the somewhat vague question, unfortunately I'm just not sure on it at all.