C++ namespace and include(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.
这篇关于C++ 命名空间和包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 命名空间和包含
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01