为什么在这里必须使用命名空间std? [英] Why using namespace std is necessary here?
问题描述
#include <iostream>
using namespace std;
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
如果删除第二条语句,构建将失败。
If I remove the 2nd statement,the build will fail.
为什么有必要?
推荐答案
因为 cout
和 endl
包含在 std
名称空间内。
Because cout
and endl
are contained inside the std
namespace.
您可以使用命名空间std 行删除行,而将
std :: cout
和 std :: endl
。
You could remove the using namespace std
line and put instead std::cout
and std::endl
.
以下示例应使命名空间清晰:
Here is an example that should make namespaces clear:
Stuff.h:
namespace Peanuts
{
struct Nut
{
};
}
namespace Hardware
{
struct Nut
{
};
}
使用命名空间硬件执行之类的操作
您可以使用Nut而不显式指定名称空间。对于使用这些类中的任何一个的任何源,它们都需要1)包括标题,以及2)指定类的名称空间或放置using指令。
When you do something like using namespace Hardware
you can use Nut without specifying the namespace explicitly. For any source that uses either of these classes, they need to 1) Include the header and 2) specify the namespace of the class or put a using directive.
命名空间的目的在于进行分组,还可以避免命名空间冲突。
The point of namespaces are for grouping and also to avoid namespace collisions.
编辑有关您为什么需要#include的问题:
#include< iostream>
包括 cout
和 endl
的源。该源位于iostream内部的名为std的名称空间内。
#include <iostream>
includes the source for cout
and endl
. That source is inside the namespace called std which is inside iostream.
这篇关于为什么在这里必须使用命名空间std?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!