【问题标题】:Purpose of Using namespace in C++在 C++ 中使用命名空间的目的
【发布时间】:2013-09-28 03:36:56
【问题描述】:

using namespace std; 包含什么内容?
IOstream 头文件中存在所有与 IO 相关的函数,为什么要同时使用 IOStream 和 Std 命名空间?

【问题讨论】:

    标签: c++ namespaces std iostream using


    【解决方案1】:

    命名空间允许在一个名称下对类、对象和函数等实体进行分组。 这样全局作用域可以划分为“子作用域”,每个子作用域都有自己的名称。

    命名空间的格式为:

     namespace identifier
     {
         entities
     }
    

    例如

    // using
    #include <iostream>
    using namespace std;
    
    namespace first
    {
      int x = 5;
      int y = 10;
    }
    
    namespace second
    {
      double x = 3.1416;
      double y = 2.7183;
    }
    
    int main () {
      using namespace first;
      cout << x << endl;
      cout << y << endl;
      cout << second::x << endl;
      cout << second::y << endl;
      return 0;
    }
    

    您可以在http://www.cplusplus.com/doc/tutorial/namespaces/阅读更多相关信息

    【讨论】:

      【解决方案2】:

      除了这里的其他答案,重要的是要注意 using 声明using 指令之间的区别。

      using namespace std;
      

      是一个using 指令,并允许在该命名空间中使用所有 名称,而无需限定。例如:

      using namespace std;
      string myStdString;
      cout << myStdString << endl;
      

      这与:

      using std::string;
      

      是一个using 声明,允许使用来自指定命名空间的特定名称,无需限定。以下将无法编译:

      using std::string;
      string myStdString; // Fine.
      cout << myStdString << endl; // cout and endl need qualification - std::
      

      using 关键字受范围约束:

      void Foo()
      {
          {
              using namespace std;
              string myStdString; // Fine.
          }
          string outOfScope; // Using directive out of scope.
          std::string qualified; // OK
      }
      

      将 using 指令放在头文件的全局范围内通常是个坏主意 - 除非您非常确定包含该文件的任何内容都不会包含冲突的类名,并且会产生讨厌的副作用。

      【讨论】:

        【解决方案3】:

        命名空间允许我们将一组全局类、对象和/或函数分组到一个名称下。如果您指定using namespace std,那么您不必在整个代码中添加std::。程序将知道在 std 库中查找对象。命名空间 std 包含标准 C++ 库的所有类、对象和函数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-22
          • 2011-07-15
          • 2011-03-13
          • 2011-05-05
          • 2011-01-02
          • 2013-09-27
          • 1970-01-01
          相关资源
          最近更新 更多