0

我的意图是在基类中创建一个空的虚函数。在派生类中重新定义该函数,以便它们返回特定子类的对象。

createShapeObjects是这里的工厂方法。

根据GOF书,工厂方法的正确实现是什么,工厂方法的正确实现是什么?

事实.h

#ifndef FACTO
#define FACTO

class PaintShapes
{
    public:
        virtual PaintShapes createShapeObjects(string arg) {};
};

class PaintTriangle : public PaintShapes
{
public:
    PaintTriangle() {}

    virtual PaintShapes createShapeObjects(string arg)
    {
        std::cout << "ddd";
        if (arg == "triangle")
            return new PaintTriangle;
    }
};

class PaintRectangle : public PaintShapes
{
public:
    PaintRectangle() {}

    virtual PaintShapes createShapeObjects(string arg)
    {
        std::cout << "eee";
        if (arg == "rectangle")
            return new PaintRectangle;
    }
};


/////
// My class which wants to paint a triangle:
/////

class MyClass
{
public:
    PaintShapes obj;
    void MyPaint()
    {
        obj.createShapeObjects("triangle");
    }
};



#endif // FACTO

主文件

#include <iostream>

using namespace std;
#include "facto.h"
int main()
{
    cout << "Hello World!" << endl;

    MyClass obj;
    obj.MyPaint();
    return 0;
}

这给出了错误:

error: could not convert '(operator new(4u), (<statement>, ((PaintTriangle*)<anonymous>)))' from 'PaintTriangle*' to 'PaintShapes'
             return new PaintTriangle;
                        ^
4

1 回答 1

4

我不明白这些。

工厂方法的目的是在不直接调用其构造函数的情况下创建派生类的实例。但是您的代码处于 Catch-22 的情况 - 例如,PaintRectangle您需要首先拥有此类对象的现有实例!我希望你能看到这无济于事。

尝试这样的事情:

class PaintShape
{
public:
    static PaintShape *createShapeObject(std::string shape);
};

class PaintTriangle : public PaintShape
{
public:
    PaintTriangle() { }
    // ...
};

class PaintRectangle : public PaintShape
{
public:
    PaintRectangle() { }
    // ...
};

//  This is our (*static*) factory method 
PaintShape *PaintShape::createShapeObject(std::string shape)
{
    if (shape == "triangle")
        return new PaintTriangle;
    if (shape == "rectangle")
        return new PaintRectangle;
    return nullptr;
};

然后你可以简单地做(例如):

std::string shape;
std::cout << "What shape would you like? ";
std::getline (std::cin, shape);
PaintShape *ps = PaintShape::createShapeObject (shape);
// ...

如果您有任何问题,请告诉我 - 请阅读有关为什么严格来说createShapeObject()应该返回std::unique_ptr.

于 2018-06-17T05:49:35.137 回答