如何重载操作数<<像 ostream 样式一样使用

How to overload operands << to use like the ostream style

本文关键字:lt 一样 样式 操作数 何重载 重载 ostream      更新时间:2023-10-16

我正在使用线程,需要用互斥锁保护std::cout操作,但我不知道如何重载操作符<<按如下顺序使用:

myOut << "hello " << 55 << " world" << false << 45.4f << std::endl;

如果有人能帮我,我会谢谢你的。

谢谢大家,但我解决了这个问题,很容易但重复,我需要做运算符<<返回一个myclass,然后使用这个返回值调用运算符<<想写多少遍就写多少遍,像这样:

    Log& operator<<(const std::string& p){
    std::lock_guard<std::mutex> locker(mutex);
    std::cout << p;
            return *this;
}
    Log& operator<<(const std::string& p){
    std::lock_guard<std::mutex> locker(mutex);
    std::cout << p.c_str();
            return *this;
}

但是需要为你想使用的任何类型重载它们只需为它创建一个全局变量