Operator overloading
From google's first hit: (assuming, of course, that you meant C++)
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)
// 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)
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;}
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
Popular Topics
Advertisement