programming.nbk: Home | Index | Next Page: C++ polymorphism | Previous Page: C++ Exception handling


 C++ operator overloading

http://www.cplusplus.com/doc/tutorial/classes2.html

type operator sign (parameters) { /*...*/ }

Here you have an example that overloads the addition operator (+). We are going to create a class to store bidimensional vectors and then we are going to add two of them: a(3,1) and b(1,2). The addition of two bidimensional vectors is an operation as simple as adding the two x coordinates to obtain the resulting x coordinate and adding the two y coordinates to obtain the resulting y. In this case the result will be (3+1,1+2) = (4,3).

// vectors: overloading operators example
#include <iostream>
using namespace std;

class my_vector {
  public:
    int x,y;
    my_vector () {};
    my_vector (int,int);
    my_vector operator + (my_vector);
};

my_vector::my_vector (int a, int b) {
  x = a;
  y = b;
}

my_vector my_vector::operator+ (my_vector param) {
  my_vector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return (temp);
}

int main () {
  my_vector a (3,1);
  my_vector b (1,2);
  my_vector c;
  c = a + b;
  cout << c.x << "," << c.y;
  return 0;
}

programming.nbk: Home | Index | Next Page: C++ polymorphism | Previous Page: C++ Exception handling


Notebook exported on Monday, 7 July 2008, 18:56:06 PM Eastern Daylight Time