Chinaunix首页 | 论坛 | 博客
  • 博客访问: 716415
  • 博文数量: 192
  • 博客积分: 2653
  • 博客等级: 少校
  • 技术积分: 1623
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-31 18:25
个人简介

How tough life is, how strong you should be!

文章分类

全部博文(192)

文章存档

2015年(1)

2014年(2)

2013年(37)

2012年(152)

分类: C/C++

2012-08-24 16:16:37

所谓namespace,是指标识符的各种可见范围。

C++标准程序库中的所有标识符都被定义于一个名为std的namespace中。

由于namespace的概念,使用C++标准程序库的任何标识符时,可以有三种选择:

1、直接指定标识符。例如std::ostream而不是ostream。完整语句如下:

std::cout << std::hex << 3.4 << std::endl;

2、使用using关键字。

using std::cout;
using std::endl;

以上程序可以写成

cout << std::hex << 3.4 << endl;

3、最方便的就是使用using namespace std;这样命名空间std内定义的所有标识符都有效(曝光)。就好像它们被声明为全局变量一样。那么以上语句可以如下写:

cout << hex << 3.4 << endl;

因为标准库非常的庞大,所程序员在选择的类的名称或函数名时就很有可能和标准库中的某个名字相同。所以为了避免这种情况所造成的名字冲突,就把标准库中的一切都被放在名字空间std中。但这又会带来了一个新问题。无数原有的C++代码都依赖于使用了多年的伪标准库中的功能,他们都是在全局空间下的。  

         所以就有了等等这样的头文件,一个是为了兼容以前的C++代码,一个是为了支持新的标准。

命名空间std封装的是标准程序库的名称,标准程序库为了和以前的头文件区别,一般不加".h"

If you are using #i nclude you don't need to put using 
namespace std because the .h files are not in any namespaces. If you want 
to use the libraries that are in a namespace you would use #i nclude 
So these codes are the same:

#i nclude

int main()
{
    cout<<"\n\"Least said\n\t\t soonest mended.\"\n\a";
    return 0;
}

#i nclude

using namespace std;


int main()
{
    cout<<"\n\"Least said\n\t\t soonest mended.\"\n\a";
    return 0;
}


#i nclude

int main()
{
    std::cout<<"\n\"Least said\n\t\t soonest mended.\"\n\a";
    return 0;
}

The only difference is that the last two you are required to use the 
namespace(which I showed two different ways of using the namespace).

阅读(1096) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~