Yes, this is a homework question but I'm hoping to be pointed in the right direction rather than obtain any kind of answer.
My task:
1. Create a 'Point' class that holds the x and y values of a point. Overload the '+' and '-' operators to work with this class.
2. Create a base class 'Shape' with a member function to calculate the area.
3. Create a 'Square' class that will overload the member function of 'Shape' to calculate the area of a square.
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <iostream>
#include <cmath>
using namespace std;
class Point{
public:
int x;
int y;
Point() {
x = 0;
y = 0;
};
Point(int xx, int yy){
x = xx;
y = yy;
}
Point operator+(const Point& pnt) {
x += pnt.x;
y += pnt.y;
return *this;
}
Point operator-(const Point& pnt) {
x -= pnt.x;
y -= pnt.y;
return *this;
}
};
class Shape{
public:
virtual void area() = 0;
};
class Square: public Shape{
Point p1, p2;
public:
double sideLenSq, areaSq, perimeterSq;
Square();
Square(const Point &pp1, const Point &pp2) {
p1 = pp1;
p2 = pp2;
}
void area() {
//My issue begins here
sideLenSq = sqrt(((p2.x - p1.x) * (p2.x - p1.x)) + ((p2.y - p1.y) * (p2.y - p1.y)));
areaSq = pow(sideLenSq, 2);
//My issue ends here
cout << "Side length: " << sideLenSq << endl;
cout << "Area of square: " << areaSq << endl;
}
};
int main() {
Point sqpnt1(25, 0);
Point sqpnt2(0, 0);
Square squ1(sqpnt1, sqpnt2);
squ1.area();
}
|
This code compiles and completes the task (printing out the area as 625), but as the overloaded '+' and '-' operators go unused I doubt the way I completed it is what's being asked of me. I commented the code segment that I'm having trouble with and I've tried replacing it with the following:
Obviously that doesn't do anything of significance but it implements the overloaded operators and does the busy work of (p2.x-p1.x) and (p2.y-p1.y), but it leaves me with a Point class containing two integers as x and y coordinates. I could simply continue the calculation from that point using the values in 'p3' as a poor way to store my mid-calculation variables using the math I currently have, but that just seems poor form. Am I looking for a conversion from an object to integer?
Apologies if this seems a little scattered, I'm just not quite sure how to ask my question super clearly as I'm not quite sure what to do at this point.