声明/定义类似cout的自定义对象的正确方法 [英] Correct way to declare/define custom cout-like object
问题描述
我创建了自己的类似 std :: cout
的对象,该对象同时写入 std :: cout
和一个日志文件。
I created my own std::cout
-like object that writes both to std::cout
and to a log file.
我目前正在头文件中定义它,但是我收到了未使用的变量警告。
I'm currently defining it like this in a header file, but I'm getting unused variable warnings.
头文件< MyLib / Log.h>
static LOut { };
static LOut lo;
template<typename T> inline LOut& operator<<(LOut& mLOut, const T& mValue)
{
std::string str{toStr(mValue)};
std::cout << str;
getLogStream() << str;
return mLOut;
}
用法:
#include <MyLib/Log.h>
...
lo << "hello!" << std::endl;
应该 lo
是静态
? lo
应该是 extern
吗?
为了解释声明类似 cout
的对象并显示主要标准库实现方式的正确方法。
Kudos for explaining the correct way of declaring a cout
-like object and showing how the main standard library implementations do it.
编辑:通过类似 cout
的对象,我的意思是一个全局变量,在包括相应的标头之后始终可用。
by cout
-like object, I mean a global variable that is always available after including the corresponding header.
推荐答案
std :: cout
只需声明如下:
namespace std {
extern ostream cout;
}
这是一个规则的全局变量;您可以自己做同样的事情。在标头中放置变量的 extern
声明;然后在源文件中定义相同的变量并将其链接到应用程序:
It is a regular global variable; you can do the same thing yourself. Put an extern
declaration of your variable in a header; then define the same variable in a source file and link it to your application:
// mylog.h
extern MyLog mylog;
// mylog.cpp
MyLog mylog(someparams);
这篇关于声明/定义类似cout的自定义对象的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!