Untitled

mail@pastecode.io avatar
unknown
plain_text
22 days ago
2.0 kB
3
Indexable
Never
#ifndef POLYGON_H
#define POLYGON_H

#include <vector>

class Point {
public:
    int x, y;
    Point(int x, int y) : x(x), y(y) {}
};

class Polygon {
private:
    std::vector<Point *> pts;
public:
    Polygon(std::vector<Point *> pts);
    Polygon(Point p1, Point p2, Point p3);
    Polygon(const Polygon &other);
    ~Polygon();
    void addPoint(Point *pt);
    Point operator[](int index);
    Polygon operator+(const Point &pt);
};

#endif

#include "Polygon.h"

Polygon::Polygon(std::vector<Point *> pts) : pts(pts) {}

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 *pt : other.pts) {
        pts.push_back(new Point(pt->x, pt->y));
    }
}

Polygon::~Polygon() {
    for (Point *pt : pts) {
        delete pt;
    }
}

void Polygon::addPoint(Point *pt) {
    pts.push_back(pt);
}

Point Polygon::operator[](int index) {
    return *(pts[index]);
}

Polygon Polygon::operator+(const Point &pt) {
    Polygon newPolygon(*this);
    newPolygon.addPoint(new Point(pt));
    return newPolygon;
}

#include "Polygon.h"
#include <iostream>

int main() {
    Point p1(0, 0);
    Point p2(1, 1);
    Point p3(2, 2);

    // Creating a polygon using the constructor with three points
    Polygon polygon1(p1, p2, p3);

    // Creating a polygon using the vector of points constructor
    std::vector<Point *> points = { &p1, &p2, &p3 };
    Polygon polygon2(points);

    // Copying polygon1 to polygon3
    Polygon polygon3(polygon1);

    // Adding a new point to polygon1
    Point p4(3, 3);
    polygon1.addPoint(&p4);

    // Using the [] operator to access points of polygon1
    for (int i = 0; i < 4; ++i) {
        Point pt = polygon1[i];
        std::cout << "Point " << i + 1 << ": (" << pt.x << ", " << pt.y << ")" << std::endl;
    }

    // Adding a point to polygon3 using the + operator
    Polygon polygon4 = polygon3 + p4;

    return 0;
}
Leave a Comment