样本工厂模式输出不显示

Sample Factory Pattern Output not displaying

我正在尝试实现 GoF 工厂模式,但出于某种原因我没有得到输出。

PS。以下所有文件均已使用 -std=gnu++14 参数编译。

下面是一个 shape.h 头文件,我在其中定义了一个(抽象)class Shape

class Shape
{
    public:
        virtual void draw() {}
};

现在我有了另一个头文件 shapes.h,我在其中编写了三个扩展 Shape class 的具体 classes。我还覆盖了每个 class 中的 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 class,在 shapefactory.h 中定义,它将根据函数中传递的参数给我一个 Shape

#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;
}
形状的 draw()

None 给出了输出。我哪里错了?

已通过将 get_shape() 的 return 类型更改为 Shape*

来修复
Shape* get_shape(string shape)
    {
        if (iequals(shape , "CIRCLE"))
            return new Circle();
        else if (iequals(shape , "SQUARE"))
            return new Square();
        else if (iequals(shape , "RECTANGLE"))
            return new Rectangle();
        else
            return NULL;
    }

同样,我也修改了Driver

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;
}