本文介绍了自定义cout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 cout 派生一个类,以便例如写入

How can I derive a class from cout so that, for example, writing to it

new_cout<< message;

等效于

cout< __FUNCTION__<< message< 消息结束< endl;

cout << __FUNCTION__ << "message" << "end of message" << endl;

推荐答案

class Log
{
public:
    Log(const std::string &funcName)
    {
        std::cout << funcName << ": ";
    }

    template <class T>
    Log &operator<<(const T &v)
    {
        std::cout << v;
        return *this;
    }

    ~Log()
    {
        std::cout << " [end of message]" << std::endl;
    }
};

#define MAGIC_LOG Log(__FUNCTION__)



Hence:

MAGIC_LOG << "here's a message";
MAGIC_LOG << "here's one with a number: " << 5;

这篇关于自定义cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:33