【问题标题】:a substitute for static in C++C++ 中静态的替代品
【发布时间】:2014-01-02 18:58:56
【问题描述】:

有没有办法在 c++ 中获取地图或列表,以通过多次调用保留其旧条目而不被定义为静态? 我正在使用多地图,问题是如果它是静态的,它只会返回第一个条目,否则我只会得到一个空地图。

here's the code :

    typedef struct mystruct_1 {
    std::string         _name;
    int             _nb_ev;
    int             _nb_oc;
    std::list<mystruct_2>   _ev;
    mystruct_1() {}
} mystruct_1_t;



typedef struct mystruct_2 {
    int    _id;
    int    _nbs;
    char **_t;
    mystruct_2() {}
} mystruct_2_t;


myclass::method_1(){
static std::map<std::string,mystruct_1> _Pat;
static std::multimap<std::string,mystruct_2> map_occ;

switch( myswitch ) {
            case _P_1 :
        {
         while( condition_1 ){
            mystruct_1 *p =  new mystruct_1();
            _Pat.insert ( std::pair<std::string ,mystruct_1>(p->_name,*p) );
            }   
        }
        break;
            case _P_2 :
        {
        std::string name;
        while( condition_2 ){
            mystruct_2 *line=new mystruct_2();
            map_occ.insert ( std::pair<std::string ,mystruct_2>(name,*line) );  
        }
        break;
       case _P_3 :
        {
        // here I need to get what was stored
        myclass::method_2();

        }
        break;
       default :
        // something else ;

}
}
myclass::method_2(){
//uses what was stored in the map and in the multimap 
}

【问题讨论】:

  • 代码或它没有发生。
  • 你能展示你的代码吗?听起来您在重复创建新的地图和列表。
  • C++03 还是 C++11?使用哪个编译器和系统?
  • 您在整个通话过程中都在询问状态。如果你想要一个可以做到这一点的函数,请创建一个functor
  • @BasileStarynkevitch,总是假设最新的。除非另有说明。

标签: c++ list map static


【解决方案1】:

你似乎创造了某种“C with classes”怪物。

那些静态变量应该是你的类的成员,例如:

class foo
{
     public:
       std::string m_String; // Not defined globally or at file scope!
};

这样,每当您为同一个 foo 实例更改 m_String 时,它都会保留其状态。

【讨论】:

    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 2012-10-11
    • 2010-12-10
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多