Untitled
unknown
plain_text
a year ago
2.1 kB
4
Indexable
Polygon.h
#ifndef POLYGON_H
#define POLYGON_H
#include <vector>
#include "Point.h"
class Polygon {
private:
std::vector<Point *> pts;
public:
Polygon(std::vector<Point *> points);
Polygon(Point p1, Point p2, Point p3);
Polygon(const Polygon &other);
~Polygon();
void addPoint(Point *point);
Point* operator[](int index);
Polygon operator+(const Point &point);
};
#endif
Polygon.cpp
#include "Polygon.h"
Polygon::Polygon(std::vector<Point *> points) : pts(points) {}
Polygon::Polygon(Point p1, Point p2, Point p3) {
pts.push_back(new Point(p1));
pts.push_back(new Point(p2));
pts.push_back(new Point(p3));
}
Polygon::Polygon(const Polygon &other) {
for (Point *p : other.pts) {
pts.push_back(new Point(*p));
}
}
Polygon::~Polygon() {
for (Point *p : pts) {
delete p;
}
}
void Polygon::addPoint(Point *point) {
pts.push_back(point);
}
Point* Polygon::operator[](int index) {
if (index >= 0 && index < pts.size()) {
return pts[index];
} else {
return nullptr;
}
}
Polygon Polygon::operator+(const Point &point) {
Polygon newPolygon(*this);
newPolygon.addPoint(new Point(point));
return newPolygon;
}
Polygonmain.cpp
#include <iostream>
#include "Polygon.h"
int main() {
std::vector<Point *> points = {new Point(0, 0), new Point(1, 0), new Point(1, 1)};
Polygon poly1(points);
Polygon poly2(Point(0, 0), Point(1, 0), Point(1, 1));
Polygon poly3(poly1);
poly3 = poly3 + Point(2, 2);
std::cout << "Points of poly1: ";
for (int i = 0; i < 3; ++i) {
Point *p = poly1[i];
if (p) {
std::cout << "(" << p->getX() << ", " << p->getY() << ") ";
}
}
std::cout << std::endl;
for (Point *p : points) {
delete p;
}
return 0;
}
Point.h
#ifndef POINT_H
#define POINT_H
class Point {
private:
int x;
int y;
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
int getX() const { return x; }
int getY() const { return y; }
};
#endif
Editor is loading...
Leave a Comment