C ++标准库:如何编写cout,cerr,cin和endl的包装器? [英] C++ Standard Library: How to write wrappers for cout, cerr, cin and endl?
本文介绍了C ++标准库:如何编写cout,cerr,cin和endl的包装器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不喜欢 using namespace std
,但我也厌倦了输入 std ::
前面每个 cout
, cin
, cerr
和 endl
。所以,我想给他们更短的新名字,像这样:
I do not like using namespace std
, but I am also tired of having to type std::
in front of every cout
, cin
, cerr
and endl
. So, I thought of giving them shorter new names like this:
// STLWrapper.h
#include <iostream>
#include <string>
extern std::ostream& Cout;
extern std::ostream& Cerr;
extern std::istream& Cin;
extern std::string& Endl;
// STLWrapper.cpp
#include "STLWrapper.h"
std::ostream& Cout = std::cout;
std::ostream& Cerr = std::cerr;
std::istream& Cerr = std::cin;
std::string _EndlStr("\n");
std::string& Endl = _EndlStr;
但是,在上面有什么问题,我错过了吗?
This works. But, are there any problems in the above which I am missing? Is there a better way to achieve the same?
推荐答案
为什么不
using std::cin;
using std::cout;
等等?然后在你的代码中,你可以使用 cin
, cout
,等等,不会意外注入所有的 std
命名空间。
and so on? Then in your code you can use cin
, cout
, and so on, without accidentally injecting all of the rest of the std
namespace into your code.
这篇关于C ++标准库:如何编写cout,cerr,cin和endl的包装器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文