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++ 命名空间和包含
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
