Java静态块的C++替代品

use*_*421 3 c++ java idioms static-initialization

我正在写一个日期类,我想要一个静态地图将"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.
Run Code Online (Sandbox Code Playgroud)

sya*_*yam 6

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

map<string, int> date::month_map = { {"Jan", 1},
                                     {"Feb", 2}
                                     // and so on
                                   };
Run Code Online (Sandbox Code Playgroud)

在C++ 03中,我相信你会坚持你现在正在做的事情.