【问题标题】:C++ alternatives to Java static blocks [duplicate]Java静态块的C ++替代品[重复]
【发布时间】:2013-04-30 18:17:46
【问题描述】:

我正在编写一个日期类,我想要一个静态地图将“Jan”映射到 1,依此类推。我想知道如何初始化该静态地图。这就是我目前正在做的事情,但我只是觉得与 Java 中的静态块相比,额外的 if 语句不优雅。我知道C++程序的编译要复杂得多,但我仍然想知道是否存在更好的解决方案。

class date {
    static map<string, int> month_map;
    int month;
    int year;
public:
    class input_format_exception {};
    date(const string&);
    bool operator< (const date&) const;
    string tostring() const;
};

map<string, int> date::month_map = map<string,int>();

date::date(const string& s) {
    static bool first = true;
    if (first)  {
        first = false;
        month_map["Jan"] = 1;
        month_map["Feb"] = 2;
        month_map["Mar"] = 3;
        month_map["Apr"] = 4;
        month_map["May"] = 5;
        month_map["Jun"] = 6;
        month_map["Jul"] = 7;
        month_map["Aug"] = 8;
        month_map["Sep"] = 9;
        month_map["Oct"] = 10;
        month_map["Nov"] = 11;
        month_map["Dec"] = 12;
    }   
    // the rest code.
}

// the rest code.

【问题讨论】:

标签: java c++ idioms static-initialization


【解决方案1】:

您可以在 C++ 中“实现”静态块功能,甚至是 C++11 之前的版本。看我的详细回答here;它会让你做的很简单

#include "static_block.hpp"

static_block {
    month_map["Jan"] = 1;
    month_map["Feb"] = 2;
    month_map["Mar"] = 3;
    month_map["Apr"] = 4;
    month_map["May"] = 5;
    month_map["Jun"] = 6;
    month_map["Jul"] = 7;
    month_map["Aug"] = 8;
    month_map["Sep"] = 9;
    month_map["Oct"] = 10;
    month_map["Nov"] = 11;
    month_map["Dec"] = 12;
}   

但是,使用初始化列表要好得多,所以如果你有 C++11 编译器,请使用 @syam 的 answer 建议的那些。

【讨论】:

    【解决方案2】:

    对于非 c++11 系统:如何使用辅助函数并使 month_map 成为 datestatic const 成员,因为看起来你永远不想改变月份的名称与它的数字的关联,你呢?这样month_map 在你的 cpp 文件中初始化,而不是在你的构造函数中,它只会把事情搞砸。 (也许你将来会有几个构造函数,那你就得写很多样板代码了)

    const std::map<string, int> createMonthMap()
    {
       std::map<string, int> result;
    
       // do init stuff
    
       return result;
    }
    
    const std::map<string, int> date::month_map(createMonthMap());
    

    【讨论】:

      【解决方案3】:

      在 C++11 中,您可以使用初始化列表:

      map<string, int> date::month_map = { {"Jan", 1},
                                           {"Feb", 2}
                                           // and so on
                                         };
      

      在 C++03 中,我相信您会被当前所做的事情所困扰。

      【讨论】:

      • 实际上,OP 并没有坚持他/她目前正在做的事情,这似乎是我的回答。除了那句话,我想给你点赞……
      猜你喜欢
      • 2015-08-26
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多