使用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.
C++中using namespace std是什么意思?
最新推荐文章于 2022-09-16 06:05:46 发布