在不同函数内的类中使用静态映射:

时间:2013-08-27 09:48:19

标签: c++ map

我有一个这样的课程:

class SelectorFactory
{
public:

    static std::map<std::string,int> _creator;  
    static void registerCreator(std::string& name,int value)
    {
    //static std::map<std::string,int> _creator;
        if(_creator.end() != _creator.find(name))
        {
           std::cout << "Selector already registered \n";
        }
    else
    {
        std::cout << "Entering " <<name<<" in register: \n";
        _creator[name]=value;
    }
    }   

    static int createSelector(std::string selectorName)
    {
    //static std::map<std::string,int> _creator;
        std::map< std::string , int >::iterator mapIter=_creator.find(selectorName);
        if(mapIter==_creator.end())
        {
            std::cout<<selectorName<<" Not found in the Map \n" ;
            return 0;
        }
        else
        {
            int selector= mapIter->second;
            return selector;
        }
    }
};

如果我取消注释上面的注释行,代码就会被编译,但是它没有从createSelector函数返回任何值,这是非常明显的。但是如果我对它们进行注释,我会收到错误,因为“_creator未在此范围内声明”在这两个功能里面。 我该怎么做才能解决这个问题。

2 个答案:

答案 0 :(得分:1)

为了实例化-creator,您必须为其提供定义。目前,您只有一份声明。

class SelectorFactory
{
    static std::map<std::string,Int> _creator;
};
std::map<std::string,Int> SelectorFactory::_creator;

答案 1 :(得分:1)

SelectorFactory.h:

#ifndef __SELECTOR_FACTORY__H__
#define __SELECTOR_FACTORY__H__
#include <string>
#include <map>

class SelectorFactory
{
public: 
    static void registerCreator(std::string& name,int value); 
    static int createSelector(std::string selectorName);
private:              // !!!!!!!!! NOT PUBLIC!!!   >:(
    static std::map<std::string,int> _creator;   

};
#endif // __SELECTOR_FACTORY__H__

SelectorFactory.cpp:

#include "SelectorFactory.h"
#include <iostream>

std::map<std::string,int> SelectorFactory::_creator; 

void SelectorFactory::registerCreator(std::string& name,int value)
{
    if(_creator.end() != _creator.find(name))
    {
        std::cout << "Selector already registered \n";
    }
    else
    {
        std::cout << "Entering " <<name<<" in register: \n";
        _creator[name]=value;
    }
}   

int SelectorFactory::createSelector(std::string selectorName)
{
    std::map< std::string , int >::iterator mapIter=_creator.find(selectorName);
    if(mapIter==_creator.end())
    {
        std::cout<<selectorName<<" Not found in the Map \n" ;
        return 0;
    }
    else
    {
        int selector= mapIter->second;
        return selector;
    }
}