【发布时间】: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.
【问题讨论】:
-
这里有一个相关问题:http://stackoverflow.com/questions/138600/initializing-a-static-stdmapint-int-in-c 这可能会帮助您了解您的选择。
-
stackoverflow.com/questions/2172053/… 还提供了额外的提示。
标签: java c++ idioms static-initialization