zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    软考
    码云
    vue和bpmnjs
    工作流引擎
    net core restapi
    工厂模式
    sqlmanage
    类的扩展
    导出excel
    拼图
  • 原文地址:https://www.cnblogs.com/bigben0123/p/14081678.html
Copyright © 2011-2022 走看看