vector.cc Testcase
-> Eine Referenz ist günstiger bei Vektoren
-> move ist ohne Referenz flexibler
-> Es werden weniger Objekte erzeugt und dementsprechend auch wieder zerstört.
committer: Markus Bröker <mbroeker@largo.homelinux.org>
/**
* DEREFERNCING CLASSES
*/
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#define GETRANDOM(max) (1+(int)((float)max*rand()/RAND_MAX+1.0))
#define MAX 6
namespace algebra {
class Vector {
private:
int x;
int y;
public:
Vector (int xx = 0, int yy = 0);
~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;
}
Vector::~Vector () {
fprintf (stderr, "Removing Vector (%.3d, %.3d)\n", x, y);
}
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[MAX];
Vector result;
srand (time (NULL));
if ((MAX % 2) != 0) {
printf ("MAX %% 2 != 0\n");
return EXIT_FAILURE;
}
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 ());
}
printf ("\nCLEANUP\n");
for (int i = 0; i < MAX; i++)
delete v[i];
return EXIT_SUCCESS;
}