namespace usage

☆樱花仙子☆ 提交于 2019-12-12 15:05:40

问题


I'm trying to start using namespaces the correct (or at least best) way.

The first thing I tried to do was to avoid putting using namespace xxx; at the beginning of my files. Instead, I want to using xxx::yyy as locally as possible.

Here is a small program illustrating this :

#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;
}

If I omit the lines using std::cout; or using std::endl, the compiler will complain when I'm trying to use cout or endl.

But why is this not needed for srand, rand and time ? I'm pretty sure they are in std, because if I try to specifically pour std:: in front of them, my code is working fine.


回答1:


If you use cstdlib et al. the names in them are placed in both the global and the std:: namespaces, so you can choose to prefix them with std:: or not. This is seen as a feature by some, and as a misfeature by others.




回答2:


If you really want to know, take a close look at the ctime and cstdlib headers. They were built backwards-compatible.

Note: all this using vs. using namespace business is about readability. If your IDE would allow to just not show the namespaces when you don't want to see them, you wouldn't need these constructs...




回答3:


I prefer to omit using and just have the std::cout every time just to maintain readability. although this is probably only useful in larger projects




回答4:


As long as we on the subject, there's also a thing called Koenig Lookup which allows you to omit a namespace identifier before a function name if the arguments it take come from the same namespace.

For example

#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;
}

Well, it's not related directly but I though it may be useful.



来源:https://stackoverflow.com/questions/2116226/namespace-usage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!