C++中“using namespace std”表示什么意思?

如题所述

使用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<int> ivect(ia,ia+arraysize);

vector<int>::iterator it1 = find(ivect.begin (),ivect.end (),4);
if(it1 == ivect.end ())
cout<<"4 not found "<<endl;
else
cout<<"4 found "<<*it1<<endl;

return 0;
}

输出结果为:4 found 4.

龙行虎步的伟岸英姿;
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网