Why use namespace if iostream is imported
我是C ++的初学者,最近我被介绍到像std这样的命名空间。 但是,如果在iostream头文件中定义了类似cout和endl的函数,为什么要包含std命名空间呢? 或者这些函数是否实际在std命名空间中定义? 如果是这种情况,那么为什么要包含iostream文件?
C ++文件中可以包含命名空间,不同的C ++文件可以在其中具有相同的命名空间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // Header1.h namespace SomeScope { extern int x; } // Header2.h namespace SomeScope { extern int y; } // Some CPP file #include"Header1.h" // access to x SomeScope::x = 5; #include"Header2.h" // access to y SomeScope::y = 6; |
我希望这有帮助。命名空间就像一个存储各种标识符的地方,以避免名称冲突。
命名空间和#include指令是不同的东西:
当您包含标题(如iostream)时,您告诉预处理器将文件的内容视为在源程序中出现包含的位置时出现这些内容。
为什么使用包含而不是仅仅在那里抛出代码?
从:
http://www.cplusplus.com/forum/articles/10627/
(1) It speeds up compile time. As your program grows, so does your
code, and if everything is in a single file, then everything must be
fully recompiled every time you make any little change. This might not
seem like a big deal for small programs (and it isn't), but when you
have a reasonable size project, compile times can take several minutes
to compile the entire program. Can you imagine having to wait that
long between every minor change?Compile / wait 8 minutes /"oh crap, forgot a semicolon" / compile /
wait 8 minutes / debug / compile / wait 8 minutes / etc(2) It keeps your code more organized. If you seperate concepts into
specific files, it's easier to find the code you are looking for when
you want to make modifications (or just look at it to remember how to
use it and/or how it works).(3) It allows you to separate interface from implementation. If you
don't understand what that means, don't worry, we'll see it in action
throughout this article.
另一方面,命名空间允许您在范围内对类和函数进行分组。它们提供了一种避免这些实体之间名称冲突的方法,而不会给处理嵌套类带来不便。
如果使用namespace std,则不必使用std :: cout。
在这种情况下写cout就足够了。