namespace的应用:
不同的命名空间可以包含相同的变量名/函数名,当使用某个头文件下的某变量/函数时,需要指定其所在的命名空间。格式:[name]::[var/fun name]
。如果频繁使用此变量/函数,可以加上语句using namespace [name]
,则引用/调用时,前面不需要再加上命名空间名了。
示例:
selfdef.h
#define A 100 #define B 200 namespace A { int a; void funA() { } } namespace B { int b; void funB() { } }
main.cpp
#inclued <iostream> #include "selfdef.h" using namespace std; int main() { cout<<A::a<<endl; cout<<B::b<<endl; }
第二段代码等价于
>#inclued <iostream> #include "selfdef.h" using namespace A; using namespace std; int main() { cout<<a<<endl; cout<<B::b<<endl; }
另外
include <>:
引用的是编译器的类库路径里面的头文件。
include "":
引用的是你程序目录的相对路径中的头文件。
有无.h的区别
:在新标准后的标准库中都有一个不带“.h”扩展名的相对应,区别除了后者的好多改进之外,还有一点就是后者的东东都塞进了“std”名字空间中。但是,string.h跟C++的string类没有任何关系,所以<string>并非<string.h>的“升级版本”,他们是毫无关系的两个头文件。