java - Java 静态 block 的 C++ 替代品

标签 java c++ idioms static-initialization

<分区>

我正在编写一个日期类,我想要一个静态 map 将“Jan”映射到 1 等等。我想知道如何初始化该静态 map 。这就是我目前正在做的,但我只是觉得与Java中的静态 block 相比,额外的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.

最佳答案

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

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

在 C++03 中,我相信你会坚持你目前正在做的事情。

关于java - Java 静态 block 的 C++ 替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16408129/

相关文章:

java - 实现重写 toString 方法的继承

javascript - dlib http 服务器将网站显示为纯 html,没有 javascript/css

javascript - 在 Javascript/JQuery 中提取多维数组

Python 嵌套循环成语

C++11 和缺少多态 lambda - 为什么?

javascript - 在 JavaScript 中处理非法参数的惯用方法是什么?

java - Web服务与java android

java - Eclipse 中的 jUnit 抛出空指针异常

java - 我如何在java中将数字放在一起?

c++ - "std::shared_from_this"不能被它的派生类继承吗?