实现了多边形类,派生了三角形类,实现如下:
头文件:
源文件
Polygon.h
#pragma once
#ifndef _Polygon_H_
#define _Polygon_H_
#include <iostream>
class Polygon
{
private:
float height;
float width;
float area;
public:
Polygon(float h = 0.0, float w = 0.0);
void Set_Height_Width(float h, float w);
void Set_Area(float a);
float GetArea() const;
float GetHeight() const;
float GetWidth() const;
virtual void Print_Polygon_Info() const;
virtual void Area();
virtual ~Polygon() {}
};
class Triangle :public Polygon
{
private:
std::string name;
public:
Triangle(float h = 0.0, float w = 0.0, std::string _name = "none");
Triangle(const Polygon& po, std::string _name = "none");
virtual void Area();
virtual void Print_Polygon_Info() const;
};
#endif
Polygon.cpp
#include "Polygon.h"
using namespace std;
Polygon::Polygon(float h, float w) :height(h), width(w) {
area = 0.0;
}
void Polygon::Set_Height_Width(float h, float w) {
height = h;
width = w;
}
float Polygon::GetHeight() const {
return height;
}
float Polygon::GetWidth() const {
return width;
}
float Polygon::GetArea() const {
return area;
}
void Polygon::Set_Area(float a) {
area = a;
}
void Polygon::Area() {
area = height * width;
}
void Polygon::Print_Polygon_Info() const {
cout << "[Polygon_area = height x width] = " << height << " x " << width << " = " << area << endl;
}
Triangle::Triangle(float h, float w, std::string _name) :Polygon(h, w) {
name = _name;
}
Triangle::Triangle(const Polygon& po, std::string _name) : Polygon(po) {
name = _name;
}
void Triangle::Area() {
float area = 0.5 * GetHeight() * GetWidth();
Set_Area(area);
}
void Triangle::Print_Polygon_Info() const {
cout << name << " [Tria_area = 0.5 x height x width] = 0.5 x " << GetHeight() << " x " << GetWidth() << " = " << GetArea() << endl;
}