头文件RegularPolygon.h
#ifndef REGULARPOLYGON_H
#define REGULARPOLYGON_H
class RegularPolygon{
public:
RegularPolygon();
~RegularPolygon();
RegularPolygon(int n, double side);
RegularPolygon(int n, double side, double x, double y);
int getN() const;
double getSide() const;
double getX() const;
double getY() const;
void setN(int n);
void setSide(double side);
void setX(double x);
void setY(double y);
double getPerimeter(); //返回周长
double getArea(); //返回面积
private:
int n; //正多边形边数
double side; //边的长度
double x; //中心x轴坐标
double y; //中心y轴坐标
};
#endif //RegularPolygon.h
实现文件RegularPolygon.cpp
#include "RegularPolygon.h"
#include <cmath>
#define PI 3.14159
RegularPolygon::RegularPolygon(): n(3), side(1), x(0), y(0){
//nothing
}
RegularPolygon::~RegularPolygon(){
//nothing
}
RegularPolygon::RegularPolygon(int n, double side){
this->n = n;
this->side = side;
}
RegularPolygon::RegularPolygon(int n, double side, double x, double y){
this->n = n;
this->side = side;
this->x = x;
this->y = y;
}
int RegularPolygon::getN() const{
return n;
}
double RegularPolygon::getSide() const{
return side;
}
double RegularPolygon::getX() const{
return x;
}
double RegularPolygon::getY() const{
return y;
}
void RegularPolygon::setN(int n){
this->n = n;
}
void RegularPolygon::setSide(double side){
this->side = side;
}
void RegularPolygon::setX(double x){
this->x = x;
}
void RegularPolygon::setY(double y){
this->y = y;
}
double RegularPolygon::getPerimeter(){
return static_cast<double>(n) * side;
}
double RegularPolygon::getArea(){
return (static_cast<double>(n) * side * side) / (4 * tan(PI / static_cast<double>(n)));
}
测试文件main.cpp
#include <iostream>
#include <iomanip>
#include "RegularPolygon.h"
using namespace std;
int main(){
RegularPolygon r1;
RegularPolygon r2(6, 4);
RegularPolygon r3(10, 4, 5.6, 7.8);
cout << setw(12) << " " << setw(12) << left << "r1";
cout << setw(12) << left << "r2" << "r3" << endl;
cout << endl;
cout << setw(12) << left << "perimeter:";
cout << setw(12) << left << r1.getPerimeter();
cout << setw(12) << left << r2.getPerimeter();
cout << setw(12) << left << r3.getPerimeter() << endl;
cout << endl;
cout << setw(12) << left << "area:";
cout << setw(12) << left << r1.getArea();
cout << setw(12) << left << r2.getArea();
cout << setw(12) << left << r3.getArea() << endl;
return 0;
}
运行结果: