adding 13

This commit is contained in:
Jidong Xiao
2024-04-16 17:00:37 -04:00
parent 1418bb2fd7
commit 6f44d26ad1
11 changed files with 668 additions and 0 deletions

View File

@@ -0,0 +1,93 @@
# Lab 13 — Multiple Inheritance & Exceptions
For this lab you will build a class inheritance structure to match the hierarchy of classic geometric shapes.
The finished program will read lists of 2D point coordinates from a file and determine the shape described
by each list of points. We will use a somewhat quirky method to determine the type of each shape. We will
pass the list of points to each specialized shape constructor in turn, and if the constructor doesnt fail, then
we know that that list of points is in fact that type of shape. Remember, the only way for a constructor to
fail is to throw an exception.
## Checkpoint 0
If you havent done so already, please complete your course evaluation for Data Structures (your honest & anonymous feedback is very important!). Have the webpage receipt saying “completed” open in your browser to receive credit for Checkpoint 0.
## Checkpoint 1: Shape Hierarchy
*estimate: 20-40 minutes*
Consider the “is-a” relationships between these 13 different shapes: Polygon, Triangle, Quadrilateral, Isosceles Triangle, Right Triangle, Isosceles Right Triangle, Equilateral Triangle, Trapezoid, Kite, Parallelogram, Rectangle, Rhombus, and Square. Note that a particular shape may be correctly labeled by more than one of these names; e.g., a Square is also a Quadrilateral.
Draw the class hierarchy with arrows indicating all of the inheritance relationships (you do not need to include the member variables or member functions). Be neat, have a consistent (up or down) orientation to your arrows, and avoid messy scribbles or cross outs and arrow crossings. Sketch the shapes in the [input.txt](cp1/input.txt) file - each line of the input file begins with a string name followed by 3 or more 2D coordinate vertices. Write the name of each shape next to the most specific type of shape it represents. Hint: you may want to grab or print yourself some graph paper.
The inheritance diagram of these shapes includes multiple inheritance, specifically in the form of the Diamond Problem. That is, Class D multiply inherits from Class B and Class C, and Class B and Class C each inherit from Class A. Thus when an object of type D is created, in turn instances of B and C are created, and unfortunately both will try to make their own instance of A. If two instances of A were allowed, attempts to refer to member variables or member functions of A would be ambiguous. To solve the problem, we should specify that B virtually inherits from A and C virtually inherits from A. Furthermore, when we construct an instance of D, in addition to specifying how to call constructors for B and C, we also explicitly specify the constructor for A.
![alt text](images/multiple_inheritance.png "Multiple Inheritance")
<!--
```cpp
class A {
public:
A() {}
};
class B : virtual public A {
public:
B() : A() {}
};
class C : virtual public A {
public:
C() : A() {}
};
class D : public B, public C {
public:
D() : A(), B(), C() {}
};
```
-->
Note how in the single inheritance example below, G only explicitly calls a constructor for F.
![alt text](images/single_inheritance.png "Single Inheritance")
<!--
```cpp
class E {
public:
E() {}
};
class F : public E {
public:
F() : E() {}
};
class G : public F {
public:
G() : F() {}
};
```
-->
Label the virtual inheritance paths in your diagram. Hint: 6 of the inheritance arrows will be labeled virtual.
**To complete this checkpoint**: Present your class inheritance diagram and your shape sketches to one of the TAs.
## Checkpoint 2:
*estimate: 20-40 minutes*
To start the implementation, well focus on just 7 of those shapes: Polygon, Triangle, Quadrilateral, Isosceles Triangle, Equilateral Triangle, Rectangle, and Square. This subset will allow us to initially ignore the multiple inheritance diamond property and the need for virtual inheritance it causes.
Download the code and initial example: [simple_main.cpp](cp2/simple_main.cpp), [utilities.h](cp2/utilities.h), [simple.txt](cp2/simple.txt), [output_simple.txt](cp2/output_simple.txt).
The program expects 2 command line arguments, the names of the input and output files. Each line of the input file begins with a string name followed by 3 or more 2D coordinate vertices. The output categorizes each shape into one or more classes, and into groups with equal angles, equal edges, and/or a right angle. The provided code includes code to call the constructors of the different classes, generally ordered from most specific/constrained to least specific. For example, the program will try to create a Square with the data first, and only if that constructor fails (throws an exception) then it will try to create a Rectangle. We also include a utilities.h file with a number of simple geometric operations: e.g., calculate the distance between two points, calculate the angle between two edges, and compare two distances or two angles and judge if they are sufficiently close to be called “equal”. Remember that you usually dont want to check if two floating point numbers are equal; instead, check if the difference is below an appropriate tolerance.
Create a polygons.h file (and optionally a polygons.cpp file). Create the 7 classes for these shapes deriving classes from the other classes as appropriate. In each constructor write code to check whether the vertices passed in meet the requirements for that shape. Throw an exception if you find a problem. Note: Just throw a value of type integer. The value thrown is unimportant in this program it will be ignored.
**To complete this checkpoint**: Compile, run, and debug your program. Study the output and confirm that your program is correctly labeling the shapes in simple.txt.
## Checkpoint 3:
*estimate: 20-30 minutes*
Now tackle the problem of multiple inheritance and the diamond property. Focus on either the [triangles](cp3/triangles.txt) or the [quadrilaterals](cp3/quads.txt) (more challenging). Here is a revised [main.cpp](cp3/main.cpp) for all shapes (comment out the portions you are not implementing).
In organizing your code for this lab, try to avoid unnecessarily duplicating code. For example, dont implement the HasARightAngle function in every class. Also, you dont need to check if the Rectangle has 4 vertices (the constructor for its base class will do that). Instead, allow the derived class to rely on the implementation of that function in its parent class. Similarly, dont recalculate measurement data if you can deduce information from properties of that shape. For example, when a Rectangle is asked if it HasARightAngle, no calculation is necessary — the answer is guaranteed to be true.
**To complete this checkpoint**: Be sure to ask your TAs for help if you get stuck. Near the end of lab period show a TA your progress.

View File

@@ -0,0 +1,31 @@
black (1,0) (0.5,0.866) (1,1.732) (3,1.732) (3.5,0.866) (3,0)
blue (0,0) (0,1) (1,1) (1,0)
brown (2,0) (0,1) (3,3)
cyan (0,0) (0,2) (1,0)
green (0,0) (0,1) (1,0)
grey (1,0) (1.5,0.866) (1,1.732) (2,1.732) (2.5,0.866) (2,0)
magenta (0,0) (1,1) (4,1) (3,0)
olive (0,0) (1,2) (6,3) (4,0)
orange (0,0) (0,3) (2,3) (2,0)
pink (1,0) (0,2) (4,2) (3,0)
purple (0,0) (0,2) (3,1)
red (0,0) (0.5,0.866) (1,0)
teal (1,0) (0,3) (1,4) (2,3)
white (2,0) (0,1) (3,4) (6,1) (4,0)
yellow (0,1) (2,2) (4,1) (2,0)

View File

@@ -0,0 +1,8 @@
7 Polygon(s): blue brown grey olive orange purple red
3 Triangle(s): brown purple red
2 IsoscelesTriangle(s): purple red
1 EquilateralTriangle(s): red
3 Quadrilateral(s): blue olive orange
2 Rectangle(s): blue orange
1 Square(s): blue
3 Shape(s) with all equal sides: blue grey red

View File

@@ -0,0 +1,7 @@
blue (0,0) (0,1) (1,1) (1,0)
brown (2,0) (0,1) (3,3)
grey (1,0) (1.5,0.866) (1,1.732) (2,1.732) (2.5,0.866) (2,0)
olive (0,0) (1,2) (6,3) (4,0)
orange (0,0) (0,3) (2,3) (2,0)
purple (0,0) (0,2) (3,1)
red (0,0) (0.5,0.866) (1,0)

View File

@@ -0,0 +1,168 @@
#include <cassert>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include "polygons.h"
// helper function prototypes
Polygon* CreatePolygon(const std::string &name, const std::vector<Point> &points);
void OutputStats(const std::vector<Polygon*> &polygons, std::ofstream &ostr);
// ------------------------------------------------------------------------------
int main(int argc, char* argv[]) {
// command line arguments & opening files
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " input.txt output.txt" << std::endl;
exit(1);
}
std::ifstream istr(argv[1]);
if (!istr) {
std::cerr << "ERROR: could not open " << argv[1] << std::endl;
exit(1);
}
std::ofstream ostr(argv[2]);
if (!ostr) {
std::cerr << "ERROR: could not open " << argv[2] << std::endl;
exit(1);
}
// the master container of polygons
std::vector<Polygon*> polygons;
// read the input file one line at a time
std::string line;
while (getline(istr,line)) {
std::stringstream ss(line);
std::string name, token;
if (!(ss >> name)) continue;
std::vector<Point> points;
while (ss >> token) {
std::stringstream ss2(token);
char c;
double x,y;
ss2 >> c;
assert (c == '(');
ss2 >> x;
ss2 >> c;
assert (c == ',');
ss2 >> y;
ss2 >> c;
assert (c == ')');
points.push_back(Point(x,y));
}
assert (points.size() >= 3);
Polygon* p = CreatePolygon(name,points);
// add the new polygon to the master container
polygons.push_back(p);
}
// write out the statistics
OutputStats(polygons,ostr);
// delete the dynamically allocated polygons
for (int i = 0; i < polygons.size(); i++) {
delete polygons[i];
}
}
// ------------------------------------------------------------------------------
// This function determines the most specific type of shape that can
// be created from the sequence of points. It does this by process of
// elimination. Note that the order in which it attempts to create
// the shapes is important.
Polygon* CreatePolygon(const std::string &name, const std::vector<Point> &points) {
Polygon *answer = NULL;
try{
answer = new EquilateralTriangle(name,points);
}
catch (int) {
try {
answer= new IsoscelesTriangle(name,points);
}
catch (int) {
try {
answer= new Triangle(name,points);
}
catch (int) {
try {
answer= new Square(name,points);
}
catch (int) {
try {
answer= new Rectangle(name,points);
}
catch (int) {
try {
answer= new Quadrilateral(name,points);
}
catch (int) {
answer= new Polygon(name,points);
}
}
}
}
}
}
assert (answer != NULL);
return answer;
}
// ------------------------------------------------------------------------------
// This function prints the output. C++ macros are used to abbreviate
// some repetitive code. The function call-like macros are actually
// replaced using substitution by the preprocessor before the code is
// given to the compiler. (You are not required to understand the
// details of the macros. You do not need to edit this code.)
void OutputStats(const std::vector<Polygon*> &polygons, std::ofstream &ostr) {
// define and initialize variables
# define InitializeCount(type) std::vector<std::string> all_##type
InitializeCount(Polygon);
InitializeCount(Triangle);
InitializeCount(IsoscelesTriangle);
InitializeCount(EquilateralTriangle);
InitializeCount(Quadrilateral);
InitializeCount(Rectangle);
InitializeCount(Square);
std::vector<std::string> equal_sides;
// count & record the names of shapes in each category
for (std::vector<Polygon*>::const_iterator i = polygons.begin(); i!=polygons.end(); ++i) {
# define IncrementCount(type) if (dynamic_cast<type*> (*i)) all_##type.push_back((*i)->getName())
IncrementCount(Polygon);
IncrementCount(Triangle);
IncrementCount(IsoscelesTriangle);
IncrementCount(EquilateralTriangle);
IncrementCount(Quadrilateral);
IncrementCount(Rectangle);
IncrementCount(Square);
if ((*i)->HasAllEqualSides()) equal_sides.push_back((*i)->getName());
}
// output data for each category, sorted alphabetically by the shape's name
# define PrintVector(vecname) std::sort((vecname).begin(),(vecname).end()); \
for (unsigned int j = 0; j < (vecname).size(); j++) { ostr << " " << (vecname)[j]; } ostr << std::endl
# define PrintCount(type) do { ostr << all_##type.size() << " " #type"(s): "; PrintVector(all_##type); } while (0)
PrintCount(Polygon);
PrintCount(Triangle);
PrintCount(IsoscelesTriangle);
PrintCount(EquilateralTriangle);
PrintCount(Quadrilateral);
PrintCount(Rectangle);
PrintCount(Square);
ostr << equal_sides.size() << " Shape(s) with all equal sides: ";
PrintVector(equal_sides);
}
// ------------------------------------------------------------------------------

View File

@@ -0,0 +1,120 @@
// =========================================
//
// IMPORTANT NOTE: DO NOT EDIT THIS FILE
//
// =========================================
#ifndef _UTILITIES_H_
#define _UTILITIES_H_
#include <iostream>
#include <cmath>
#include <cassert>
// epsilon values used in comparing the edge lengths & angles between
// edges note that these values are dependent on the precision of
// the coordinates and the overall scale of the objects
#define DISTANCE_EPSILON 0.0001
#define ANGLE_EPSILON 0.1
// -----------------------------------------------------------------
// Stores a 2D coordinate
class Point {
public:
Point(double _x, double _y) : x(_x),y(_y) {}
double x;
double y;
};
// Stores a 2D vector, constructed from 2 Points
class Vector {
public:
Vector(const Point &a, const Point &b) { dx = b.x-a.x; dy = b.y-a.y; }
double Length() const { return sqrt(dx*dx+dy*dy); }
void Normalize() {
// make this a unit vector (length = 1)
double length = Length();
if (length < DISTANCE_EPSILON) throw std::string("LENGTH = 0");
assert (length > DISTANCE_EPSILON);
dx /= length;
dy /= length;
}
// representation
double dx;
double dy;
};
inline std::ostream& operator<< (std::ostream &ostr, const Vector &v) {
ostr << "<" << v.dx << "," << v.dy << ">";
return ostr;
}
// -----------------------------------------------------------------
// calculate the length of an edge, the distance between 2 points
inline double DistanceBetween(const Point &a, const Point &b) {
Vector v(a,b);
return v.Length();
}
// Calculate the angle at vertex b in degrees, that is, the angle
// between edges ab and bc. This will return a positive number
// measured as the clockwise rotation in the xy plane from point c to
// point a (rotating around point b).
inline double Angle(const Point &a, const Point &b, const Point &c) {
// make unit vector along each of the edges
Vector ba(b,a); ba.Normalize();
Vector bc(b,c); bc.Normalize();
// calculate the angle in radians
double dot_product = ba.dx * bc.dx + ba.dy * bc.dy;
if (dot_product < -1 || dot_product > 1) throw std::string("DOT PRODUCT RANGE");
assert (dot_product >= -1 && dot_product <= 1);
float perpDot = ba.dx * bc.dy - ba.dy * bc.dx;
// using atan2 to ensure than we get a signed answer.
double angle_in_radians = atan2(perpDot, dot_product);
// convert to degrees
double answer = angle_in_radians * 180.0 / M_PI;
if (answer < 0) {
answer += 360;
}
assert (answer >= 0 && answer <= 360);
return answer;
}
// returns true if these two vectors are parallel
inline bool Parallel(const Vector &a, const Vector &b) {
Vector a2 = a; a2.Normalize();
Vector b2 = b; b2.Normalize();
double dot_product = a2.dx * b2.dx + a2.dy * b2.dy;
// parallel vectors have dot product == 1
if (fabs(dot_product) > 1-DISTANCE_EPSILON) return true;
return false;
}
// -----------------------------------------------------------------
// simple functions for angles & sides
inline bool EqualSides(double a, double b) {
return (fabs(a-b) < DISTANCE_EPSILON);
}
inline bool EqualAngles(double a, double b) {
assert (a >= 0.0 && a < 360.0);
assert (b >= 0.0 && b < 360.0);
return (fabs(a-b) < ANGLE_EPSILON);
}
inline bool RightAngle(double a) {
assert (a >= 0.0 && a < 360.0);
return (fabs(a-90.0) < ANGLE_EPSILON);
}
// -----------------------------------------------------------------
#endif

View File

@@ -0,0 +1,223 @@
#include <cassert>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include "polygons.h"
// helper function prototypes
Polygon* CreatePolygon(const std::string &name, const std::vector<Point> &points);
void OutputStats(const std::vector<Polygon*> &polygons, std::ofstream &ostr);
// ------------------------------------------------------------------------------
int main(int argc, char* argv[]) {
// command line arguments & opening files
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " input.txt output.txt" << std::endl;
exit(1);
}
std::ifstream istr(argv[1]);
if (!istr) {
std::cerr << "ERROR: could not open " << argv[1] << std::endl;
exit(1);
}
std::ofstream ostr(argv[2]);
if (!ostr) {
std::cerr << "ERROR: could not open " << argv[2] << std::endl;
exit(1);
}
// the master container of polygons
std::vector<Polygon*> polygons;
// read the input file one line at a time
std::string line;
while (getline(istr,line)) {
std::stringstream ss(line);
std::string name, token;
if (!(ss >> name)) continue;
std::vector<Point> points;
while (ss >> token) {
std::stringstream ss2(token);
char c;
double x,y;
ss2 >> c;
assert (c == '(');
ss2 >> x;
ss2 >> c;
assert (c == ',');
ss2 >> y;
ss2 >> c;
assert (c == ')');
points.push_back(Point(x,y));
}
assert (points.size() >= 3);
Polygon* p = CreatePolygon(name,points);
// add the new polygon to the master container
polygons.push_back(p);
}
// write out the statistics
OutputStats(polygons,ostr);
// delete the dynamically allocated polygons
for (int i = 0; i < polygons.size(); i++) {
delete polygons[i];
}
}
// ------------------------------------------------------------------------------
// This function determines the most specific type of shape that can
// be created from the sequence of points. It does this by process of
// elimination. Note that the order in which it attempts to create
// the shapes is important.
Polygon* CreatePolygon(const std::string &name, const std::vector<Point> &points) {
Polygon *answer = NULL;
try{
answer = new EquilateralTriangle(name,points);
}
catch (int) {
try {
answer= new IsoscelesRightTriangle(name,points);
}
catch (int) {
try {
answer= new RightTriangle(name,points);
}
catch (int) {
try {
answer= new IsoscelesTriangle(name,points);
}
catch (int) {
try {
answer= new Triangle(name,points);
}
catch (int) {
try {
answer= new Square(name,points);
}
catch (int) {
try {
answer= new Rectangle(name,points);
}
catch (int) {
try {
answer= new Rhombus(name,points);
}
catch (int) {
try {
answer= new Parallelogram(name,points);
}
catch (int) {
try {
answer= new Kite(name,points);
}
catch (int) {
try {
answer= new Trapezoid(name,points);
}
catch (int) {
try {
answer= new Quadrilateral(name,points);
}
catch (int) {
answer= new Polygon(name,points);
}
}
}
}
}
}
}
}
}
}
}
}
assert (answer != NULL);
return answer;
}
// ------------------------------------------------------------------------------
// This function prints the output. C++ macros are used to abbreviate
// some repetitive code. The function call-like macros are actually
// replaced using substitution by the preprocessor before the code is
// given to the compiler. (You are not required to understand the
// details of the macros. You do not need to edit this code.)
void OutputStats(const std::vector<Polygon*> &polygons, std::ofstream &ostr) {
// define and initialize variables
# define InitializeCount(type) std::vector<std::string> all_##type
InitializeCount(Polygon);
InitializeCount(Triangle);
InitializeCount(IsoscelesTriangle);
InitializeCount(RightTriangle);
InitializeCount(IsoscelesRightTriangle);
InitializeCount(EquilateralTriangle);
InitializeCount(Quadrilateral);
InitializeCount(Trapezoid);
InitializeCount(Kite);
InitializeCount(Parallelogram);
InitializeCount(Rhombus);
InitializeCount(Rectangle);
InitializeCount(Square);
std::vector<std::string> equal_sides;
std::vector<std::string> equal_angles;
std::vector<std::string> right_angle;
// count & record the names of shapes in each category
for (std::vector<Polygon*>::const_iterator i = polygons.begin(); i!=polygons.end(); ++i) {
# define IncrementCount(type) if (dynamic_cast<type*> (*i)) all_##type.push_back((*i)->getName())
IncrementCount(Polygon);
IncrementCount(Triangle);
IncrementCount(IsoscelesTriangle);
IncrementCount(RightTriangle);
IncrementCount(IsoscelesRightTriangle);
IncrementCount(EquilateralTriangle);
IncrementCount(Quadrilateral);
IncrementCount(Trapezoid);
IncrementCount(Kite);
IncrementCount(Parallelogram);
IncrementCount(Rhombus);
IncrementCount(Rectangle);
IncrementCount(Square);
if ((*i)->HasAllEqualSides()) equal_sides.push_back((*i)->getName());
if ((*i)->HasAllEqualAngles()) equal_angles.push_back((*i)->getName());
if ((*i)->HasARightAngle()) right_angle.push_back((*i)->getName());
}
// output data for each category, sorted alphabetically by the shape's name
# define PrintVector(vecname) std::sort((vecname).begin(),(vecname).end()); \
for (unsigned int j = 0; j < (vecname).size(); j++) { ostr << " " << (vecname)[j]; } ostr << std::endl
# define PrintCount(type) do { ostr << all_##type.size() << " " #type"(s): "; PrintVector(all_##type); } while (0)
PrintCount(Polygon);
PrintCount(Triangle);
PrintCount(IsoscelesTriangle);
PrintCount(RightTriangle);
PrintCount(IsoscelesRightTriangle);
PrintCount(EquilateralTriangle);
PrintCount(Quadrilateral);
PrintCount(Trapezoid);
PrintCount(Kite);
PrintCount(Parallelogram);
PrintCount(Rhombus);
PrintCount(Rectangle);
PrintCount(Square);
ostr << equal_sides.size() << " Shape(s) with all equal sides: ";
PrintVector(equal_sides);
ostr << equal_angles.size() << " Shape(s) with all equal angles: ";
PrintVector(equal_angles);
ostr << right_angle.size() << " Shape(s) with a right angle: ";
PrintVector(right_angle);
}
// ------------------------------------------------------------------------------

View File

@@ -0,0 +1,9 @@
blue (0,0) (0,1) (1,1) (1,0)
orange (0,0) (0,3) (2,3) (2,0)
yellow (0,1) (2,2) (4,1) (2,0)
magenta (0,0) (1,1) (4,1) (3,0)
pink (1,0) (0,2) (4,2) (3,0)
teal (1,0) (0,3) (1,4) (2,3)
olive (0,0) (1,2) (6,3) (4,0)

View File

@@ -0,0 +1,9 @@
red (0,0) (0.5,0.866) (1,0)
green (0,0) (0,1) (1,0)
cyan (0,0) (0,2) (1,0)
purple (0,0) (0,2) (3,1)
brown (2,0) (0,1) (3,3)

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB