I have a shape class with each shape having a coordinate for where its located. I have overloaded the - operator to calculate distance but it doesnt return the correct value. Any clues?
//Main file with figure pointer to the derived class functions
#include <iostream>
#include "shape.h"
#include "rectangle.h"
#include "triangle.h"
#include "circle.h"
#include "square.h"
using namespace std;
void SortShape(Shape* arr[], int n);
int main()
{
Shape *shapes[5];
Triangle tri(Blue, 50, 50, 5.0, 10.0);
Circle circ1(Green, 30, 30, 5);
Circle circ2(Red, 50, 50, 10);
Rectangle rect(Violet, 15, 15, 5, 10);
Square sq(Orange, 0, 0, 7);
shapes[0] = &tri;
shapes[1] = &circ1;
shapes[2] = &circ2;
shapes[3] = ▭
shapes[4] = &sq;
for(int i = 0; i < 5; ++i)
{
shapes[i]->drawObject();
cout << "Area of shape[" << i << "]: " << shapes[i]->getArea() << endl;
shapes[i]->getAttr();
cout << "Distance between Shape[" << i << "] and Shape[" << 1 << "]: " << shapes[i] - shapes[1] << endl;
}
SortShape(shapes, 5);
cout << endl;
cout << "Sorted Shape Array by Area:" << endl;
for(int i = 0; i < 5; ++i)
{
shapes[i]->ResetLocation(2, 2);
shapes[i]->drawObject();
cout << "Area of shape[" << i << "]: " << shapes[i]->getArea() << endl;
shapes[i]->getAttr();
}
return 0;
}
void SortShape(Shape* arr[], int n)
{
bool swapped = true;
int j = 0;
Shape *tmp;
while (swapped)
{
swapped = false;
j++;
for (int i = 0; i < n - j; i++)
{
if (arr[i]->getArea() > arr[i + 1]->getArea())
{
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
swapped = true;
}
}
}
}
//shape.h
//shape base class declaration header file
//virtual commented out for first run, uncommented on second run
#ifndef SHAPE_H
#define SHAPE_H
#include <iostream>
#include <cmath>
using namespace std;
enum Color{Red, Orange, Yellow, Green, Blue, Indigo, Violet};
void getColor(Color col);
class Shape
{
public:
Shape():color(Yellow), x(0), y(0){};/*{cout << "Figure Default Constructor" << endl;}*/
Shape(Color col, int X, int Y):color(col), x(X), y(Y){};
Shape(const Shape& rhs):color(rhs.color), x(rhs.x), y(rhs.y){};
virtual ~Shape(){};
virtual void ResetLocation(int deltaX, int deltaY)
{
x = deltaX;
y = deltaY;
}
virtual void getAttr()
{
cout << "X: " << x << " Y: " << y << " Color: ";
getColor(color);
}
virtual void ResetColor(Color col){color = col;}
virtual double getArea() = 0;
virtual void drawObject(){};
float operator-(const Shape& rhs)
{
float v = ((x - rhs.x)*(x - rhs.x)) + ((y - rhs.y)*(y - rhs.y));
float z = sqrt(v);
return z;
}
protected:
Color color;
int x;
int y;
};
void getColor(Color col)
{
switch(col)
{
case 0:
cout << "Red" << endl;
break;
case 1:
cout << "Orange" << endl;
break;
case 2:
cout << "Yellow" << endl;
break;
case 3:
cout << "Green" << endl;
break;
case 4:
cout << "Blue" << endl;
break;
case 5:
cout << "Indigo" << endl;
break;
case 6:
cout << "Violet" << endl;
break;
}
}
#endif