C++ 命名空间和包含 [英] C++ namespace and include

查看:26
本文介绍了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.

还请注意,您不需要 using - 您可以使用 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天全站免登陆