点、直线和矩形的类
class Point
{
public:
int x;
int y;
};
class Line
{
public:
Point start;
Point end;
Line(const Point& start, const Point& end)
{
this->start = start;
this->end = end;
}
};
class Rect
{
public:
Point leftUp;
int width;
int height;
Rect(const Point& leftUp, int width, int height)
{
this->leftUp = leftUp;
this->width = width;
this->height = height;
}
};
MainForm类
class MainForm
{
private:
vector<Line> lineVector;
vector<Rect> rectVector;
public:
void addLine(const Line& line) { lineVector.push_back(line); }
void addRect(const Rect rect) { rectVector.push_back(rect); }
void run();
};
void MainForm::run()
{
// 画直线
for (int i = 0; i < lineVector.size(); i ++ )
{
drawLine(
red,
lineVector[i].start.x,
lineVector[i].start.y;
lineVector[i].end.x;
lineVector[i].end.y;
);
}
// 画矩形
for (int i = 0; i < rectVector.size(); i ++ )
{
drawRect(
red,
rectVector[i].leftUp,
rectVector[i].width,
rectVector[i].height
);
}
}
不难发现我们如果需要增加一个画圆形的方法就要修改MainForm
类的很多代码
Shape抽象类、点、直线和矩形的类
class Shape
{
public:
virtual void draw() = 0;
virtual ~Shape() {};
};
class Point
{
public:
int x;
int y;
};
class Line : public Shape
{
public:
Point start;
Point end;
Line(const Point& start, const Point& end)
{
this->start = start;
this->end = end;
}
void draw()
{
drawLine(
red,
start.x,
start.y,
end.x,
end.y
);
}
};
class Rect : public Shape
{
public:
Point leftUp;
int width;
int height;
Rect(const Point& leftUp, int width, int height)
{
this->leftUp = leftUp;
this->width = width;
this->height = height;
}
void draw()
{
drawRect(
red,
rectVector[i].leftUp,
rectVector[i].width,
rectVector[i].height
);
}
};
MainForm类
class MainForm
{
private:
// 使用基类指针
vector<Shape*> ShapeVector;
public:
void add(Shape* shape)
{
ShapeVector.push_back(shape);
}
void run();
};
void MainForm::run()
{
// 只需要调用虚函数方法
for (int i = 0; i < ShapeVector.size(); i ++ )
{
ShapeVector[i]->draw();
}
}