我的意图是在基类中创建一个空的虚函数。在派生类中重新定义该函数,以便它们返回特定子类的对象。
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;
^