Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Design patterns 工厂模式输出示例未显示_Design Patterns_C++14_Factory Pattern - Fatal编程技术网

Design patterns 工厂模式输出示例未显示

Design patterns 工厂模式输出示例未显示,design-patterns,c++14,factory-pattern,Design Patterns,C++14,Factory Pattern,我试图实现GoF工厂模式,但由于某些原因,我没有得到输出 下面的所有文件都是用-std=gnu++14参数编译的 下面是一个shape.h头文件,我在其中定义了一个(抽象)类shape class Shape { public: virtual void draw() {} }; 现在我有了另一个头文件shapes.h,其中我编写了三个扩展Shape类的具体类。我还重写了每个类中的draw() #include "shape.h" #include <iostre

我试图实现GoF工厂模式,但由于某些原因,我没有得到输出

下面的所有文件都是用-std=gnu++14参数编译的

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

class Shape
{
    public:
        virtual void draw() {}
};
现在我有了另一个头文件
shapes.h
,其中我编写了三个扩展
Shape
类的具体类。我还重写了每个类中的
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";
        }
};
最后是我们的驱动程序:

#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()
均未提供输出。我哪里出错了?

通过将get\u shape()的返回类型更改为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;
    }
同样,我还必须修改驱动程序

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