In: Computer Science
Study the file polygon.h. It contains the header file for a class of regular polygons. Implement the methods, and provide a driver to test it. It should be in C++
polygon.h file-
#ifndef POLY_RVC_H
#define POLY_RVC_H
#include <iostream>
using namespace std;
class Polygon
{
public:
Polygon();
Polygon(int n, double l);
//accessors - all accessors should be declared
"const"
// usually, accessors are also inline functions
int getSides() const { return sides; }
double getLength() const { return length; }
// function to set values (mutator)
void setPoly(int n, double l);
void setSides(int n);
void setLength(double l);
bool operator< (const Polygon & rhs)
const
{
return area() <
rhs.area();
}
double area() const;
double perimeter() const;
private:
int sides;
double length;
};
ostream& operator << (ostream& outs, const
Polygon& d);
bool operator == (const Polygon& p1, const Polygon&
p2);
#include "poly_imp.cpp"
#endif
Note: While running if you get compile error please comment #include "poly_imp.cpp" in header file(polygon.h).
poly_imp.cpp
#include<iostream>
#include"polygon.h"
using namespace std;
// Default constructor
Polygon::Polygon()
{
sides=0;
length=0;
}
// Parametrized constructor
Polygon::Polygon(int n, double l)
{
sides=n;
length=l;
}
// Set the polygon
void Polygon ::setPoly(int n, double l)
{
sides=n;
length=l;
}
// Set the sides of the polygon
void Polygon::setSides(int n)
{
sides=n;
}
// Set the length of polygon
void Polygon::setLength(double l)
{
length=l;
}
// Comput area of polygon
double Polygon:: area() const
{
return
(length*length*sides)/(4*tan(3.14/sides));
}
// Compute perimeter of polygon
double Polygon::perimeter() const
{
return sides*length;
}
//Print the output
ostream& operator << (ostream& outs, const
Polygon& d)
{
outs<<"Number of sides:
"<<d.getSides()<<endl;
outs<<"Length of one side:
"<<d.getLength()<<endl;
outs<<"Area of polygon:
"<<d.area()<<endl;
outs<<"Perimeter of polygon:
"<<d.perimeter()<<endl;
return outs;
}
// Comparison
bool operator == (const Polygon& p1, const Polygon&
p2)
{
if((p1.getSides()==p2.getSides()) &&
(p1.getLength()==p2.getLength()))
return true;
else
return false;
}
main.cpp
#include<iostream>
#include "polygon.h"
void main()
{
// First polygon
cout<<"First Polygon:"<<endl;
Polygon p(7,6);
cout<<p;
cout<<endl;
// Second polygon
cout<<"Second Polygon:"<<endl;
Polygon p1;
p1.setSides(7);
p1.setLength(6);
cout<<p1;
cout<<endl;
// Check both are equal
if(p==p1)
cout<<"Both polygons are
equal"<<endl;
else
cout<<"Both polygons are not
equal"<<endl;
system("pause");
}
Output: