目录
1、main.cpp
#include <iostream>
#include <string>
#include "Shape.h"
#include "circle.h"
#include "rectangle.h"
using namespace std;
int main() {
Shape s1{Color::blue,false};
Circle c1{3.9,Color::green,true};
Rectangle r1{4.0,1.0,Color::white,true };
cout << s1.toString() << endl;
cout << c1.toString() << endl;
cout << r1.toString() << endl;
return 0;
}
2、circle.cpp
#include <iostream>
#include "circle.h"
Circle::Circle(){
radius = 1.0;
}
Circle::Circle(double radius_, Color color_, bool filled_) : Shape{color_,filled_} {
radius = radius_;
}
double Circle::getArea() {
return (3.14 * radius * radius);
}
double Circle::getRadius() const {
return radius;
}
void Circle::setRadius(double radius) {
this->radius = radius;
}
3、circle.h
#pragma once
#include "Shape.h"
class Circle : public Shape{
double radius;
public:
Circle();
Circle(double radius_, Color color_, bool filled_);
double getArea();
double getRadius() const;
void setRadius(double radius);
};
4、rectangle.cpp
#include "rectangle.h"
Rectangle::Rectangle(double w, double h, Color color_, bool filled_) :width{ w }, height{h}, Shape{ color_,filled_ } {}
double Rectangle::getWidth() const { return width; }
void Rectangle::setWidth(double w) { width = w; }
double Rectangle::getHeight() const { return height; }
void Rectangle::setHeight(double h) { height = h; }
double Rectangle::getArea() const { return width * height; }
5、rectangle.h
#pragma once
#include "Shape.h"
class Rectangle : public Shape {
private:
double width{1.0};
double height{1.0};
public:
Rectangle() = default;
Rectangle(double w, double h, Color color_, bool filled_);
double getWidth() const;
void setWidth(double w);
double getHeight() const;
void setHeight(double h);
double getArea() const;
};
6、Shape.h
#pragma once
#include <iostream>
#include <string>
#include <array>
using std::string;
using namespace std::string_literals;
enum class Color {
white , black , read , green , blue , yellow,
};
class Shape {
private:
Color color{Color::black};
bool filled{false};
public:
Shape() = default;
Shape(Color color_, bool filled_)
{
color = color_;
filled = filled_;
}
Color getColor() { return color; }
void setColor(Color color_) { color = color_; }
bool isFilled() { return filled; }
void setFilled(bool filled_) {filled = filled_;}
string toString() {
std::array<string, 6> c{ "white"s,"black"s,"red"s,"green"s,"blue"s,"yellow"s,};
return "Shape: " + c[static_cast<int>(color)] + " " + (filled ? "filled"s : "not filled"s);
}
};