获取链接 创建flyweight_pattern时出错

getting linking Error while creating a flyweight_pattern

本文关键字:pattern 出错 flyweight 链接 创建 获取      更新时间:2023-10-16
#include <iostream>
#include <map>
#include <string>
#include <cstdlib>
using namespace std;
class Shape 
{
public :
virtual void draw()=0;
virtual ~Shape(){}
};
class Circle : public Shape
{
string color;
int x;
int y;
int radius;
public:
Circle(string color){
color = color;        
}
void setX(int x) {
x = x;
}
void setY(int y) {
y = y;
}
void setRadius(int radius) {
radius = radius;
}
void draw() {
cout << "color :" << color << x << y ; 
}
};
class ShapeFactory {
public:
static map<string, Shape*> circlemap;
static Shape* getcircle(string color)
{
Shape *mcircle;
mcircle = circlemap.find(color)->second;
if(mcircle == nullptr) {
mcircle = new Circle(color);
circlemap[color] = mcircle;
// circlemap.insert(std::make_pair(color,mcircle));
}
return mcircle;
}
};
class Flyweightpattern
{
public:
static string getRandomColor(string colors[]) {
int m_rand = rand() % 5; 
return colors[m_rand];
}
static int getRandomX() {
return (int)(rand() % 100);
}
static int getRandomY() {
return (int)(rand() % 100);
}
};
int main()
{
string colors[] = { "Red", "Green", "Blue", "White", "Black" };
for(int i=0; i < 20; ++i) {
Circle *circle = dynamic_cast<Circle *>(ShapeFactory::getcircle(Flyweightpattern::getRandomColor(colors)));
circle->setX(Flyweightpattern::getRandomX());
circle->setY(Flyweightpattern::getRandomY());
circle->setRadius(100);
circle->draw();
}
getchar();
return 0;
}

我在运行期间收到以下链接错误:

flyweight_pattern.obj:错误LNK2001:未解析的外部符号 "public: 静态类 std::map,class std::分配器>,类圈 *,结构标准::更少,类标准::分配器>>,类 标准::分配器,类 标准::分配器> 常量,类 Circle *>>> ShapeFactory::circlemap" (?circlemap@ShapeFactory@@2V?$map@V?$basic_string@

DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAVCircle@@U?$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@@PAVCircle@@@std@@@2@@std@@A(

我在 ShapeFactory 类中有一个地图,并尝试在类本身中创建填充地图,但仍然无法解决问题。

你没有定义 circlemap,它是一个静态成员,所以你应该在全局范围内定义它(并初始化(:

map<string, Shape*> ShapeFactory::circlemap = {};

积分非易失性静态成员可以在类中初始化。

哦,不建议在全球范围内做using namespace std;,这会导致副作用。

你可以写一些类似的东西

using std::map; 

以目标为目标 ID(在本例中为 map(,您可以在包含用法的命名空间中编写 using 。