强调了抽象的概念,而不是分而治之,上代码
#include <iostream>
#include <vector>
class Shape
{
public:
? ? virtual void draw() = 0;
? ? virtual ~Shape() {}
};
class Point : public Shape
{
public:
? ? Point()
? ? {
? ? }
? ? ~Point()
? ? {
? ? }
? ? virtual void draw()
? ? {
? ? ? ? std::cout << "use Point" << std::endl;
? ? }
};
class Line : public Shape?
{
public:
? ? Line()
? ? {
?
? ? }
? ? ~Line()
? ? {
? ? }
? ? virtual void draw()
? ? {
? ? ? ? std::cout << "use line" << std::endl;
? ? }
};
class Rect : public Shape
{
public:
? ? Rect()
? ? {
? ? }
? ? ~Rect()
? ? {
? ? }
? ? virtual void draw()
? ? {
? ? ? ? std::cout << "use Rect" << std::endl;
? ? }
};
int main()
{
? ? Shape* ptShape = new Point;?
? ? Shape* lineShape = new Line;
? ? Shape* rectShape = new Rect;
? ? std::vector<Shape*> shapeVector; //这里Shape要用指针,多态性
? ? shapeVector.push_back(ptShape);
? ? shapeVector.push_back(lineShape);
? ? shapeVector.push_back(rectShape);
? ? for (auto& theShape : shapeVector) ?//针对各种形状,各负其责
? ? {
? ? ? ? theShape->draw();
? ? }
? ??
? ? delete ptShape;
? ? ptShape = nullptr;
? ? delete lineShape;
? ? lineShape = nullptr;
? ? delete rectShape;
? ? rectShape = nullptr;
? ? return 0;
}
?
打印结果是:
use Point
use line
use Rect
?
这里用了抽象类,
如果分而治之,则会需要3个数组,分别判断具体属于哪个类,是点,圆还是线,再调用相应类的方法。如果再添加,还需要再加数组,1万个种类的图形则需要1万种数组