最近在读C++ Primer Fourth Edition。偶然发现cout和std::cout很有意思。一个是需要引用iostream.h,而另一个需要调用iostream。但他们的功能却又差不多。

当你使用std::时,则表明你在告诉编译器你正在调用标准命名空间(namespace standard)。下面将列举出几种调用cout的例子:

1)

view plaincopy to clipboardprint?

   1. #include <iostream> 
   2.  
   3. int main() 
   4. { 
   5.     using std::cout;    using std::endl; 
   6.      
   7.     cout << "Hello, world" << endl; 
   8.      
   9.     return 0; 
  10. } 

#include <iostream> int main() { using std::cout; using std::endl; cout << "Hello, world" << endl; return 0; }

2)

view plaincopy to clipboardprint?

   1. #include <iostream> 
   2.  
   3.     using namespace std; 
   4.     
   5. int main() 
   6. { 
   7.  
   8.     cout << "Hello, world" << endl; 
   9.  
  10.     return 0; 
  11. } 

#include <iostream> using namespace std; int main() { cout << "Hello, world" << endl; return 0; }

3)

view plaincopy to clipboardprint?

   1. #include <iostream> 
   2.  
   3. int main() 
   4. { 
   5.     std::cout << "Hello, world" << std::endl; 
   6.  
   7.     return 0; 
   8. } 

#include <iostream> int main() { std::cout << "Hello, world" << std::endl; return 0; }

至于这三种形式的区别,那就属于个人风格的问题了。

至于#include <iostream>和#include <iostream.h>,后者并非标准的C头文件。并且它指向的是整个iostream库,而前者则需要我们制定命名空间,从而避免了重复名称的混乱。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐