c++ 實現 cout 示例

 

#include <iostream>
#include <sstream>
#include <string>
class CMyStream {
    public:
        typedef void (CMyStream::* EndlCallback)();
        CMyStream& operator<<(EndlCallback pEndlCallback);

        template<typename T>
        CMyStream& operator<<(T Val) { //buffer the Val into stringstream
            std::stringstream ss;
            ss << Val;
            m_str += ss.str();
            return *this;
        }

        void MyEndl(); //use std::cout to output
        
    private:
        std::string m_str;
};

CMyStream::EndlCallback endl = &CMyStream::MyEndl;

CMyStream& CMyStream::operator<<(CMyStream::EndlCallback pEndlCallback) {
    (this->*pEndlCallback)();
    return *this;
}

void CMyStream::MyEndl(void) {
    std::cout << m_str << std::endl;
    m_str = "";
}

int main() {
    CMyStream cout;
    cout << "hello" << endl;
    cout << "world";//call CMyStream& operator<<(T Val)
    cout <<endl; // endl = &CMyStream::MyEndl 
    //=> so endl is a functor 
    //=> call CMyStream& operator<<(EndlCallback pEndlCallback) override 
    //=>  in function:     (this->*pEndlCallback)();
    //=> at last call to: void CMyStream::MyEndl(void){...}
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章