C++ 命名空间和包含
为什么我们在 C++ 程序中同时需要 using namespace
和 include
指令?
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.
相关文章