tags:

views:

75

answers:

1

here is code example for add two vectors using classes

#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;
}

it is a bit difficult for me to understand it and also how often it is used in daily?

+4  A: 

The important point is by being able to overload the + symbol you can write operations involving things other than numbers in the same way as regular maths.

Rather than having to write vector_add(a,b,c) you can just write c=a+b;

edit - it's easy to get carried away though. Adding two vectors makes sense - it's pretty unambiguous, although multiplication of vectors isn't (do you mean per-element, dot-product or cross-product? )
The problem is when people just learn this and start overloading addition for database records or division for strings - to have their own meaning.

edit2 - it's also slightly more complicated to use in practice. The above example makes unecessary copies of the data, you need to know more about references and const for a real world use.

Martin Beckett