下面的所有文件都是用-std=gnu++14参数编译的。
下面是
shape.h
Shape
class Shape
{
public:
virtual void draw() {}
};
现在我有了另一个头文件
shapes.h
我写了三个具体的类来扩展
形状
上课。我也超越了
draw()
在每个班级里。
#include "shape.h"
#include <iostream>
using std::cout;
class Circle : public Shape
{
public:
void draw()
{
cout << "Inside Circle::draw()\n";
}
};
class Square : public Shape
{
public:
void draw()
{
cout << "Inside Square::draw()\n";
}
};
class Rectangle : public Shape
{
public:
void draw()
{
cout << "Inside Rectangle::draw()\n";
}
};
现在我有一个
Shapefactory
shapefactory.h
那会给我一个
形状
#include "shapes.h"
#include <string>
#include <algorithm>
using std::string;
class Shapefactory
{
private:
bool iequals(const string& a, const string& b)
{
return std::equal
(a.begin(), a.end(),
b.begin(), b.end(),
[](char a, char b) {
return tolower(a) == tolower(b);
}
);
}
public:
Shape get_shape(string shape)
{
if (iequals(shape , "CIRCLE"))
return Circle();
else if (iequals(shape , "SQUARE"))
return Square();
else if (iequals(shape , "RECTANGLE"))
return Rectangle();
else
return Circle();
}
};
最后是我们的驱动程序:
#include "shapefactory.h"
int main()
{
Shapefactory shapeFactory;
Shape shape1 = shapeFactory.get_shape("CIRCLE");
shape1.draw();
Shape shape2 = shapeFactory.get_shape("RECTANGLE");
shape2.draw();
Shape shape3 = shapeFactory.get_shape("SQUARE");
shape3.draw();
return 0;
}
没有一个形状是
绘制()