强调了抽象的概念,而不是分而治之,上代码
#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万种数组
本文地址:https://blog.csdn.net/directx3d_beginner/article/details/107570052
如对本文有疑问, 点击进行留言回复!!
纵横字谜的答案 Crossword Answers, ACM/ICPC World Finals 1994, UVa232
HDU - 5880 Family View (AC自动机修改母串)
iOS14Beta3续航怎么样 iOS14Beta3续航能力介绍
iOS14Beta3稳定性怎么样 iOS14Beta3升级建议介绍
uniapp编写H5界面放入IOS全面屏原生导航栏盖住H5界面
网友评论