vector.cc
author Markus Bröker <mbroeker@largo.dyndns.tv>
Thu, 16 Apr 2009 12:51:15 +0200
changeset 79 1499176750b9
parent 77 49e0babccb23
permissions -rw-r--r--
Little Typo in daemon.c committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * vector.cc
 * Copyright (C) 2008 Markus Broeker
 *
 * Dereferencing Classes
 */

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>

#define GETRANDOM(max) (1+(int)((float)(max)*rand()/RAND_MAX+1.0))
#define MAX 6

static int refCounter = 0;

namespace algebra {
    class Vector {
      private:
        int x;
        int y;

      public:
        Vector (int xx = 0, int yy = 0);
        Vector (const Vector &);
       ~Vector ();

        int X () { return x; };
        int Y () { return y; };

        Vector operator+ (Vector &);
        Vector operator- (Vector &);

        void vector ();
        double abs ();
    };

    Vector::Vector (int xx, int yy) {
        x = xx;
        y = yy;

        refCounter++;
    }

    Vector::Vector (const Vector & copy)
    : x (copy.x), y (copy.y) {
        fprintf (stderr, "Warning Copy Constructor\n");
        refCounter++;
    }

    Vector::~Vector () {
        fprintf (stderr, "Removing Vector (%.3d, %.3d)\n", x, y);
        refCounter--;
    }

    Vector Vector::operator+ (Vector & v) {
        return Vector (x + v.X (), y + v.Y ());
    }

    Vector Vector::operator- (Vector & v) {
        return Vector (x - v.X (), y - v.Y ());
    }

    double Vector::abs () {
        return sqrt (x * x + y * y);
    }

    void Vector::vector () {
        printf ("(%.3d, %.3d)", x, y);
    }
}

using namespace algebra;

int main (int argc, char **argv)
{
    Vector **v;
    Vector result;

    srand (time (NULL));

    if ((MAX % 2) != 0) {
        printf ("MAX %% 2 != 0\n");
        return EXIT_FAILURE;
    }

    v = new Vector *[MAX];

    for (int i = 0; i < MAX; i++) {
        v[i] = new Vector (GETRANDOM (100), GETRANDOM (100));
    }

    for (int i = 0; i < MAX; i += 2) {
        v[i + 1]->vector ();
        printf ("+");
        v[i]->vector ();
        printf ("=");
        result = *v[i + 1] + *v[i];
        result.vector ();
        printf (" = %3.2f\n", result.abs ());
    }

    printf ("\n");

    for (int i = 0; i < MAX; i += 2) {
        v[i + 1]->vector ();
        printf ("-");
        v[i]->vector ();
        printf ("=");
        result = *v[i + 1] - *v[i];
        result.vector ();
        printf (" = %3.2f\n", result.abs ());
    }

    for (int i = 0; i < MAX; i++)
        delete v[i];

    delete [] v;

    fprintf (stderr, "Objects remaining on exit: %d\n", refCounter);

    return EXIT_SUCCESS;
}