Java静态块的c++替代品
C++ alternatives to Java static blocks
我正在编写一个日期类,我想要一个静态映射映射"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的答案建议的那些
相关文章:
- C++中原子的替代品<variant>
- C++sscanf_s的替代品
- getline的替代品
- 什么是 std::function::argument_type 的替代品?
- 有DirectShow的替代品吗?
- 智能指针作为 QObject::d eleteLater() 的替代品
- C++中 mktime 的替代品
- 对于C++,是否有任何现代的 std::strchr() 替代品?
- shared_future是<void>condition_variable的合法替代品吗?
- 这是山塔的替代品
- STD :: Referent_wrapper/std :: std :: vector的selution_ptr替代品
- 更好的替代品?
- 排序向量上 std::find_if 和 std::bind2nd 的替代品
- 提升勒让德多项式的 gsl_sf_legendre_sphPlm_array() 替代品
- 标准::矢量的高性能替代品
- c++线程池:std::函数的替代品,用于将函数/lambdas传递给线程
- SHGetSpecialFolderLocation是否有新的替代品?
- cstdlib 的 rand() 的替代品
- Borland Developer Studio的开源替代品
- std::set的替代品(可以将元素从一个集合移动到另一个集合)