Overloadig operator on a class

Taken from this websites example on classesII.

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
28
29
// 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 test(0, 8);
  CVector result;
  result = foo + bar;
  cout << result.x << ',' << result.y << '\n';
  return 0;
}

This is what I don't understand.
1
2
3
4
5
6
CVector CVector::operator+ (const CVector& param) {
  CVector temp;
  temp.x = x + param.x; 
  temp.y = y + param.y;
  return temp;
}


USing the reference below. The Cvector::.. is what gives the value to x and y? and cvector &param is what gives the value to param.x and param.y?

So it could be read asCvector foo::operator+ (const CVector& bar)?



a@b + - * / % ^ & | < > == != <= >= << >> && || , A::operator@(B) operator@(A,B)

Last edited on
Cvector::operator+ just means that you want to define operator+ that is part of the class Cvector. You can use this technique to define any member function outside the class definition. If you had defined operator+ inside the class definition it would have looked something like this:

1
2
3
4
5
6
7
8
9
10
11
12
class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int a,int b) : x(a), y(b) {}
    CVector operator+(const CVector& param) {
      CVector temp;
      temp.x = x + param.x; 
      temp.y = y + param.y;
      return temp;
    }
};


Your understanding of what happens seems to be right. An alternative way of writing line 25 is result = foo.operator+(bar);.
param is a reference to the second operand (bar). The operator is called on the first argument (this points to the first operand) so x and y are therefore the coordinates of the first operand (foo).
Topic archived. No new replies allowed.