2017-07-30 40 views
0
#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類中有一個映射,並嘗試在類中創建填充地圖,但仍無法解決問題。

+0

剛剛定義靜態成員[示例](http://cpp.sh/4cznb) –

回答

0

你沒有定義circlemap,這是一個靜態成員,所以你應該在全球範圍內定義它(並初始化):

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

積分非易失性靜態成員可以在課堂上進行初始化。

哦,不建議在全球範圍內做using namespace std;,這會導致副作用。

你可以寫類似

using std::map; 

目標選擇的ID(地圖在這種情況下),你可以使用在包含使用命名空間寫。

+0

哎呀,是的,我忘了初始化它,初始化解決了這個問題,謝謝! – user2230832

相關問題