我知道我一定遗漏了一个你似乎无法发现的细节,然后一个月后它会击中你“Evrika!”。
基本上,我要做的是为形状实现一个抽象工厂类,但我不断收到与从我的形状工厂代码创建的 .obj 相关的 LKN2019 错误消息。
它看起来有点像这样:
形状工厂.h
#ifndef SHAPEFACTORY_H__
#define SHAPEFACTORY_H__
#include <iostream>
#include <map>
#include <string>
#include "shape.h"
#include "circle.h"
#include "rectangle.h"
#include "triangle.h"
using namespace std;
typedef Shape *(createShapeFunction)(void);
class ShapeFactory
{
public:
static void registerFunction(const string &, const createShapeFunction *);
static Shape *createShape(const string &);
static Shape *createShape(istream &);
private:
static map <string, createShapeFunction *> creationFunctions;
ShapeFactory();
static ShapeFactory *getShapeFactory();
};
#endif
形状工厂.cpp
#include "shapefactory.h"
void ShapeFactory::registerFunction(const string & ID, const crateShapeFunction * CR )
{
creationFunctions[ID] = CR;
}
Shape* ShapeFactory::createShape(const string & shapeName)
{
map <string, crateShapeFunction *>::iterator it = creationFunctions.find(shapeName);
if( it != creationFunctions.end() )
return it->second();
return NULL;
}
Shape* ShapeFactory::createShape(istream & in)
{
string shapeName;
cout << "Desired figure: ";
in >> shapeName;
map <string, crateShapeFunction *>::iterator it = creationFunctions.find(shapeName);
if( it != creationFunctions.end() )
return it->second();
return NULL;
}
ShapeFactory::ShapeFactory()
{
registerFunction("circle", &Circle::Create);
registerFunction("rectangle", &Rectangle::Create);
registerFunction("triangle", &Triangle::Create);
}
ShapeFactory* ShapeFactory::getShapeFactory()
{
static ShapeFactory instance;
return &instance;
}
我可能在方法的实现中搞砸了,但我根本看不到在哪里。任何形式的及时帮助将不胜感激。
编辑:错误看起来像这样
错误 4 错误 LNK2001:未解析的外部符号“私有:静态类 std::map,class std::allocator >,class Shape * (__cdecl*)(void),struct std::less,class std::allocator > >,类 std::allocator,类 std::allocator > const ,类 Shape * (__cdecl*)(void)> > > ShapeFactory::creationFunctions" (?creationFunctions@ShapeFactory@@0V?$map@V?$basic_string@DU ?$char_traits@D@std@@V?$allocator@D@2@@std@@P6APAVShape@@XZU?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@ D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@ @P6APAVShape@@XZ@std@@@2@@std@@A) C:\Proj1\shapefactory.obj
在按照 alexrider 的建议在我的标题中定义地图之前。谢谢 - 现在可以了。