Overloading operators in Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 // overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int a,int b) : x(a), y(b) {}
    CVector operator + (const CVector&);
};

CVector CVector::operator+ (const CVector& param) {
  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return temp;
}

int main () {
  CVector foo (3,1);
  CVector bar (1,2);
  CVector result;
  result = foo + bar;
  cout << result.x << ',' << result.y << '\n';
  return 0;
}




so in this example it used this syntax A::operator+(B)
and on this code CVector CVector::operator+ (const CVector& param)
it's pretty obvious that B would be the "param" but i don't get where is A
or how does CVector becomes A...


I hope someone explain this to me cause I'm really confused here.. I really don't get it..
if you use member function syntax, it looks like:
<Class operator belongs to (left hand side)>::operator+(<class you are adding (right hand side)>)
In that case A + B is the same as A.operator+(B)

However it is way better to declare every operator aside from assigment as freestanding functions.
X operator+(A lhs, B rhs)
Last edited on
OK i now got it...
sorry for bumping my thread up...
thanks anyways
Last edited on
Topic archived. No new replies allowed.