命名空间使用 [英] namespace usage

查看:105
本文介绍了命名空间使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图开始使用命名空间正确的(或至少是最好的)方式。

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

我试图做的第一件事是避免将使用命名空间xxx; 在我的文件的开头。

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

如果使用std :: cout忽略行 ; 使用std :: endl ,编译器会抱怨当我试图使用 cout endl

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.

但是为什么不需要 srand rand 时间?我确定他们在 std ,因为如果我试图特别注入 std :: ,我的代码工作正常。

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.

推荐答案

如果你使用cstdlib等。它们中的名称都放在global和std :: namespaces中,因此可以选择使用std ::作为前缀。这被某些人看作是一个特征,并且被其他人误认为。

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.

这篇关于命名空间使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆