Public Group

This topic is 4888 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

ok I understand the use of this but can someone give a real easy example?

##### Share on other sites
In what programming language?

##### Share on other sites
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)

##### Share on other sites
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;}

##### Share on other sites
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+=()).

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 26
• 9
• 11
• 9
• 9
• ### Forum Statistics

• Total Topics
633716
• Total Posts
3013499
×