C ++名称空间,包括 [英] C++ namespace and include

查看:88
本文介绍了C ++名称空间,包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在C ++程序中同时需要using namespaceinclude指令?

Why do we need both using namespace and include directives in C++ programs?

例如

#include <iostream>

using namespace std;

int main() {
 cout << "Hello world";
}

为什么仅仅拥有#include <iostream>或仅仅拥有using namespace std并摆脱另一个是不够的?

Why is it not enough to just have #include <iostream> or just have using namespace std and get rid of the other?

(我想到的是Java的类比,其中import java.net.*将从java.net导入所有内容,您无需执行其他任何操作.)

(I am thinking of an analogy with Java, where import java.net.* will import everything from java.net, you don't need to do anything else.)

推荐答案

C++中,概念是分开的.这是设计使然并且有用的.

In C++ the concepts are separate. This is by design and useful.

您可以包含没有名称空间的内容会变得模棱两可的内容.

You can include things that without namespaces would be ambiguous.

使用命名空间,您可以引用两个具有相同名称的不同类.当然,在这种情况下,您将不会使用using指令,或者如果您这样做了,则必须在所需的名称空间中指定其他内容的名称空间.

With namespaces you can refer to two different classes that have the same name. Of course in that case you would not use the using directive or if you did you would have to specify the namespace of the other stuff in the namespace you wanted.

还请注意,您不需要使用-您可以只使用std :: cout或任何需要访问的内容.您可以使用命名空间在项目前添加

Note also that you don't NEED the using - you can just used std::cout or whatever you need to access. You preface the items with the namespace.

这篇关于C ++名称空间,包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆