Operator overloading

Started by
3 comments, last by SiCrane 18 years, 9 months ago
ok I understand the use of this but can someone give a real easy example?
Advertisement
In what programming language?
From google's first hit: (assuming, of course, that you meant C++)
// vectors: overloading operators example#include <iostream.h>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;}


This is a really easy example and it was really easy to find *hint* *hint*.
If you need explanation, visit the site where I found it and read it and if there is still something unclear then you can ask us :)
I'm willing to explain it in detail (although I might go to sleep soon but I'm sure there will be others)
Now get down on your hands and knees and start repeating "Open Source Good, M$ Evil", smacking your head against the pavement after each repetition. Once you have completed your training you may change your first name to GNU/, to show that you are free from the slavery of the closed source world. -Michalson
FWIW, it's generally considered better to implement binary operators as (possibly friend) non-member functions. Among other things, it enables conversion on the left argument.

class CVector {public:    int x,y;    CVector () {};    CVector (int,int);    friend CVector operator + (const CVector&, const CVector&);};CVector::CVector (int a, int b) {  x = a;  y = b;}CVector operator+ (const CVector& lhs, const CVector& rhs) {  return CVector(lhs.x+rhs.x, lhs.y+rhs.y);}int main () {  CVector a (3,1);  CVector b (1,2);  CVector c;  c = a + b;  cout << c.x << "," << c.y;  return 0;}
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Um, Fruny, you just friended a non-member function that only uses public variables. Also if you implement the binary operator+(), you should really implement operator+=() (and strongly consider implementing operator+() in terms of operator+=()).

This topic is closed to new replies.

Advertisement