#include <iostream> //画笔抽象类 class Pen { public: virtual ~Pen(); public: virtual void PrintProstect() const = 0; virtual void PrintContext() const = 0; }; Pen::~Pen() {} //画笔A class PenA : public Pen { public: virtual ~PenA() override; public: virtual void PrintProstect() const override; virtual void PrintContext() const override; }; PenA::~PenA() {} void PenA::PrintProstect() const { std::cout << "*"; } void PenA::PrintContext() const { std::cout << "@"; } //画笔B class PenB : public Pen { public: virtual ~PenB() override; public: virtual void PrintProstect() const override; virtual void PrintContext() const override; }; PenB::~PenB() {} void PenB::PrintProstect() const { std::cout << "!"; } void PenB::PrintContext() const { std::cout << "#"; } //图形抽象类 class Graph { public: Graph(Pen& Pen); virtual ~Graph(); public: virtual void Print() const = 0; protected: Pen& _pen; }; Graph::Graph(Pen& pen) : _pen(pen) {} Graph::~Graph() {} //三角形 class Triange : public Graph { public: Triange(Pen& Pen, int length); virtual ~Triange() override; public: virtual void Print() const override; private: int _length; }; Triange::Triange(Pen& pen, int length) : Graph(pen), _length(length) {} Triange::~Triange() {} void Triange::Print() const { int between = 1; int edge = _length / 2; int num = _length / 2; for(int i = 1; i <= num; ++i) { for(int j = 1; j <= edge; ++j) { _pen.PrintContext(); } for(int k = 1; k <= between; ++k) { _pen.PrintProstect(); } for(int j = 1; j <= edge; ++j) { _pen.PrintContext(); } std::cout << std::endl; between+=2; --edge; } } //正方形 class Shape : public Graph { public: Shape(Pen& pen, int wide, int high); virtual ~Shape() override; public: virtual void Print() const override; private: int _wide; int _high; }; Shape::Shape(Pen& pen, int wide, int high) : Graph(pen), _wide(wide), _high(high) {} Shape::~Shape() {} void Shape::Print() const { for(int j = 1; j <= _high; ++j) { for(int i = 1; i <= _wide; ++i) { _pen.PrintProstect(); } std::cout << std::endl; } } int main() { PenA pen_a; PenB pen_b; Triange triange1(pen_a, 10); triange1.Print(); Triange triange2(pen_b, 10); triange2.Print(); Shape shape1(pen_a, 10, 5); shape1.Print(); Shape shape2(pen_b, 10, 5); shape2.Print(); }
运行结果:
@@@@@*@@@@@ @@@@***@@@@ @@@*****@@@ @@*******@@ @*********@ #####!##### ####!!!#### ###!!!!!### ##!!!!!!!## #!!!!!!!!!# ********** ********** ********** ********** ********** !!!!!!!!!! !!!!!!!!!! !!!!!!!!!! !!!!!!!!!! !!!!!!!!!!