是否可以取消部分默认构造函数初始化?我当前的默认构造函数如下所示:
Jd::Jd() {
time_t utcTime = time(NULL);
struct tm tmLocal;
localtime_s( &tmLocal, &utcTime );
jd_ = gregorian_to_jd(
tmLocal.tm_year + 1900,
tmLocal.tm_mon + 1,
tmLocal.tm_mday,
tmLocal.tm_hour,
tmLocal.tm_min,
tmLocal.tm_sec
);
}
我正在使用两个常量来初始化我的Jd对象:WTIMEOFDAY和NOTIMEOFDAY。
Jd const NOTIMEOFDAY;
Jd const WTIMEOFDAY;
我想将NOTIMEOFDAY初始化为默认构造对象,但只使用gregorian_to_jd()方法的年,月和日部分而不是整个事物。这可能吗?
编辑:Jd类中的构造函数
Jd();
Jd( jdn_t jdn ) : jd_( jdn ) { } //Sets the internal datamember to whatever is passed in.
//Jd( bool includeTime );
我得到的错误是:
error C2668: 'calendar::Jd::Jd' : ambiguous call to overloaded function
could be 'calendar::Jd::Jd(bool)
or 'calendar::Jd::Jd(calendar::jdn_t)
答案 0 :(得分:2)
添加另一个带参数的构造函数:
Jd::Jd(int year, int month, int day, int hour, int min, int sec)
{
jd_ = gregorian_to_jd(year, month, day, hour, min, sec);
}
创建常量时:
const Jd NOTIMEOFDAY(2013, 10, 12, 0, 0, 0); // new constructor called
const Jd WTIMEOFDAY; // default constructor called
或者您可以使用此方法:
Jd::Jd(bool includeTime = true)
{
time_t utcTime = time(NULL);
struct tm tmLocal;
localtime_s( &tmLocal, &utcTime );
jd_ = gregorian_to_jd(
tmLocal.tm_year + 1900,
tmLocal.tm_mon + 1,
tmLocal.tm_mday,
includeTime ? tmLocal.tm_hour : 0,
includeTime ? tmLocal.tm_min : 0,
includeTime ? tmLocal.tm_sec : 0);
}
然后初始化你的常量:
const Jd NOTIMEOFDAY((bool)false);
const Jd WTIMEOFDAY;
或......
// this will allow your double version to work
Jd::Jd(jdn_t jdn, bool includeTime = true)
{
// assuming what jdn_t looks like, so you'd have to make some adjustments
jd_ = gregorian_to_jd(
jdn.tm_year + 1900,
jdn.tm_mon + 1,
jdn.tm_mday,
includeTime ? jdn.tm_hour : 0,
includeTime ? jdn.tm_min : 0,
includeTime ? jdn.tm_sec : 0);
}
或......
// this should fix the whole issue and is probably the better solution
class Jd
{
// other members
public:
explicit Jd(bool includeTime); // prevent implicit conversion
explicit Jd(jdn_t jdn); // also prevents implicit conversion
};
Jd::Jd(bool includeTime) // no default parameter
{
time_t utcTime = time(NULL);
struct tm tmLocal;
localtime_s( &tmLocal, &utcTime );
jd_ = gregorian_to_jd(
tmLocal.tm_year + 1900,
tmLocal.tm_mon + 1,
tmLocal.tm_mday,
includeTime ? tmLocal.tm_hour : 0,
includeTime ? tmLocal.tm_min : 0,
includeTime ? tmLocal.tm_sec : 0);
}