代码之家  ›  专栏  ›  技术社区  ›  Jérôme

命名空间用法

  •  3
  • Jérôme  · 技术社区  · 15 年前

    我正在尝试以正确的(或至少是最好的)方式开始使用名称空间。

    我想做的第一件事就是避免 using namespace xxx; 在我文件的开头。相反,我想 using xxx::yyy 尽可能在当地。

    下面是一个小程序说明:

    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    int main() {
       using std::cout;
       using std::endl;
    
       srand(time(0));
    
       for(int i=0; i<10;++i)
          cout << rand() % 100 << endl;
    
       return 0;
    }
    

    如果我漏掉了台词 using std::cout; using std::endl 当我试图使用 cout endl .

    但为什么不需要这个 srand , rand time ?我很确定他们在 std 因为如果我想特别倒酒 std:: 在他们面前,我的代码运行良好。

    4 回复  |  直到 15 年前
        1
  •  6
  •   anon    15 年前

    如果使用cstdlib等人它们中的名称同时放置在全局和std::名称空间中,因此您可以选择在它们前面加上std::或不加前缀。这被一些人视为一个特征,而被其他人视为一个错误的特征。

        2
  •  3
  •   xtofl Adam Rosenfield    15 年前

    如果你真的想知道,仔细看看 ctime cstdlib 标题。它们是向后兼容的。

    注意:所有这些 using VS using namespace 商业是关于可读性的。如果你的IDE允许 显示 当您不想看到这些名称空间时,就不需要这些构造…

        3
  •  3
  •   Stowelly    15 年前

    我更喜欢省略使用,每次只让std::cout保持可读性。尽管这可能只在大型项目中有用

        4
  •  0
  •   Serge    15 年前

    只要我们谈这个问题,还有一件事叫 Koenig Lookup 如果函数名前面的参数来自同一个名称空间,则可以省略该名称空间标识符。

    例如

    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    void f(int i){std::cout << i << " ";}
    int main(int argc, char** argv)
    {
       std::vector<int> t;
       // for_each is in the std namespace but there's no *std::* before *for_each*
       for_each(t.begin(), t.end(), f); 
       return 0;
    }
    

    好吧,这不是直接的关系,但我认为它可能有用。