C ++:关于使用空间std和cout问题 [英] C++: Questions about using namespace std and cout
问题描述
为什么需要使用命名空间std 来输入;
,以便能够使用 COUT
和 ENDL
?也有这些东西叫做;为 COUT
函数?
Why do I need to type in using namespace std;
in order to be able to use cout
and endl
? Also what are these called; is cout
a function?
有 COUT
用C?我听说这是用C ++实现,因为它在许多方面是更好的。
Is there cout
in C? I heard it was implemented in C++ because it is better in many ways.
推荐答案
COUT
是 STD $ C $定义一个全局对象C>命名空间和
ENDL
是(流操纵)函数在 STD
命名空间还定义的。
cout
is a global object defined in the std
namespace, and endl
is a (stream manipulator) function also defined in the std
namespace.
如果你不采取任何行动,以他们的名字导入到全局命名空间,你将不能够引用它们与不合格的标识符 COUT
和 ENDL
。你必须使用完全合格的名称:
If you take no action to import their names into the global namespace, you won't be able to refer to them with the unqualified identifiers cout
and endl
. You have to use the fully qualified names:
std::cout << "Hello, World!" << std::endl;
基本上,使用命名空间std
确实被注入存在于 STD
命名实体的所有名称进入全局命名空间:
Basically, what using namespace std
does is to inject all the names of entities that exist in the std
namespace into the global namespace:
using namespace std;
cout << "Hello, Wordl!" << endl;
但是,请记住,在全局命名空间这样的使用
指令是一个 BAD 编程实践,这几乎肯定会导致邪恶的名称冲突即可。
However, keep in mind that have such a using
directive in the global namespace is a BAD programming practice, which will almost certainly lead to evil name clashes.
如果您的真正的需要使用它(例如,如果你的一个功能是使用在 STD
命名空间中定义的多种功能以及写作的std ::
使得code难读),你倒是应该限制其范围的各个功能的局部范围:
If you really need to use it (e.g. if a function of yours is using many functions defined in the std
namespace, and writing std::
makes the code harder to read), you should rather restrict its scope to the local scope of individual functions:
void my_function_using_a_lot_of_stuff_from_std()
{
using namespace std;
cout << "Hello, Wordl!" << endl;
// Other instructions using entities from the std namespace...
}
好多了,只要这是实际的,是使用以下,创伤小的 using声明的,可以指定将的选择的进口只有名称:
Much better, as long as this is practical, is to use the following, less invasive using declarations, which will selectively import only the names you specify:
using std::cout;
using std::endl;
cout << "Hello, Wordl!" << endl;
这篇关于C ++:关于使用空间std和cout问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!