Custom manipulator for class

后端 未结 4 1680
轮回少年
轮回少年 2021-01-27 07:21

I\'m trying to write a stream manipulator with arguments. I have class with 3 int\'s CDate(Year, Month, Day). So I need to make manipulator date_format(const char*)

4条回答
  •  逝去的感伤
    2021-01-27 07:46

    As chris suggested, I'd say that you should just use tm rather than your custom date class:

    tm a{0, 0, 0, 15, 5, 2006 - 1900};
    
    cout << put_time(&a, "%Y-hello-%d-world-%m-something-%d%d");
    

    If you must implement come custom functionality that cannot be accomplished with get_time and put_time then you'd probably want to use a tm member as part of your class so you could just extend the functionality that is already there:

    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");
    }
    

    You could then use CDate as follows:

    CDate a(2006, 5, 15);
    
    cout << "DATE IS:" << a;
    

    EDIT:

    After looking at your question again, I think that you have a misconception about how the insertion operator works, you cannot pass in both an object and a format: https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx

    If you want to specify a format but still retain your CDate class, I'd again suggest the use of put_time:

    cout << put_time(&a.getDate(), "%Y-hello-%d-world-%m-something-%d%d");
    

    If you again insist on writing your own format accepting function you'll need to create a helper class that can be constructed inline and support that with the insertion operator:

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

    You could use this as follows:

    cout << put_CDate(&a, "%Y-hello-%d-world-%m-something-%d%d") << endl;
    

提交回复
热议问题