c++ 中的using namespace std是什么意思啊

来源:百度知道 编辑:UC知道 时间:2024/06/02 21:08:08
有什么用

使用std命名空间

98年以后的c++语言提供一个全局的命名空间namespace,可以避免导致全局命名冲突问题。举一个实例,请注意以下两个头文件:

// one.h
char func(char);
class String { ... };

// somelib.h
class String { ... };

如果按照上述方式定义,那么这两个头文件不可能包含在同一个程序中,因为String类会发生冲突。
所谓命名空间,是一种将程序库名称封装起来的方法,它就像在各个程序库中立起一道道围墙。比如:
// one.h
namespace one
{
char func(char);
class String { ... };
}

// somelib.h
namespace SomeLib
{
class String { ... };
}

现在就算在同一个程序中使用String类也不会发生冲突了,因为他们分别变成了:one::String()以及Somelib::String()

这样,就可以通过声明命名空间来区分不同的类或函数等了。
比如C++标准库定义了命名空间:std,其中包含容器vector,示例如下:
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main(int argc, char* argv[])
{
const int arraysize = 7;
int ia[arraysize] = {0,1,2,3,4,5};

file://定义容器vector
vector&