正如克里斯建议的那样,我想说你应该只使用tm
而不是你的自定义日期类:
tm a{0, 0, 0, 15, 5, 2006 - 1900};
cout << put_time(&a, "%Y-hello-%d-world-%m-something-%d%d");
如果您必须实现无法实现的自定义功能,get_time
那么put_time
您可能希望将tm
成员用作类的一部分,以便您可以扩展已经存在的功能:
class CDate{
tm m_date;
public:
CDate(int year, int month, int day): m_date{0, 0, 0, day, month, year - 1900}{}
const tm& getDate() const{return m_date;}
};
ostream& operator<<(ostream& lhs, const CDate& rhs){
auto date = rhs.getDate();
return lhs << put_time(&a, "%Y-hello-%d-world-%m-something-%d%d");
}
然后你可以使用CDate
如下:
CDate a(2006, 5, 15);
cout << "DATE IS:" << a;
编辑:
再次查看您的问题后,我认为您对插入运算符的工作方式有误解,您不能同时传入对象和格式:https://msdn.microsoft.com/en-us/library/1z2f6c2k。 aspx
如果您想指定格式但仍保留您的CDate
课程,我再次建议使用put_time
:
cout << put_time(&a.getDate(), "%Y-hello-%d-world-%m-something-%d%d");
如果您再次坚持编写自己的格式接受函数,则需要创建一个可以内联构造的辅助类并使用插入运算符支持它:
class put_CDate{
const CDate* m_pCDate;
const char* m_szFormat;
public:
put_CDate(const CDate* pCDate, const char* szFormat) : m_pCDate(pCDate), m_szFormat(szFormat) {}
const CDate* getPCDate() const { return m_pCDate; }
const char* getSZFormat() const { return m_szFormat; }
};
ostream& operator<<(ostream& lhs, const put_CDate& rhs){
return lhs << put_time(&rhs.getPCDate()->getDate(), rhs.getSZFormat());
}
您可以按如下方式使用它:
cout << put_CDate(&a, "%Y-hello-%d-world-%m-something-%d%d") << endl;