Java静态块的c++替代品

C++ alternatives to Java static blocks

本文关键字:替代品 c++ 静态块 Java      更新时间:2023-10-16

我正在编写一个日期类,我想要一个静态映射映射"Jan"到1,等等。我想知道如何初始化静态映射。这就是我目前正在做的,但我只是觉得额外的if语句与Java中的静态块相比不美观。我知道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中,我相信你会被你目前正在做的事情所困住。

对于非c++11系统:如何使用辅助函数并使month_map a date的静态const成员,因为看起来您永远不想更改月份名称与其数字的关联,不是吗?这样,month_map在您的cpp-File中初始化,而不是在您的构造函数中,它只是把事情搞砸了。(也许你将来会有几个构造函数,那么你将不得不编写大量的样板代码)

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());

您可以在c++中"实现"静态块特性,甚至在c++ 11之前。在这里查看我的详细答案;它可以让你简单地

#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的答案建议的那些