#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
flyweight_pattern.obj:錯誤LNK2001:解析外部符號 「市民:靜態類的std ::地圖,class std :: allocator>,類Circle *,struct std :: less,class std :: allocator>>, std :: allocator,class std :: allocator> const,class Circle *> >> ShapeFactory :: circlemap「 (?circlemap @ ShapeFactory @@ 2V?$ map @ V $ $ basic_string @ DU?$ char_traits @ D @ std @@ V $ $ allocator @ D @ 2 @@ std @@ PAVCir CLE @@ U&$ @少V'$ basic_string的@ DU?$ char_traits @ d @ @@ STD V'$分配器@ d @ @@ 2 STD @@@ 2 @ V'$分配器@ U&$對@ $ $ CBV?$ basic_string的@ DU?$ char_traits @ d @ @@ STD V'$分配器@ d @ @@ 2 STD @@ PAVCircle @@@ STD @@@ 2 @@ STD @@ A)
我在ShapeFactory類中有一個映射,並嘗試在類中創建填充地圖,但仍無法解決問題。
剛剛定義靜態成員[示例](http://cpp.sh/4cznb) –