命名空间namespace的作用使得可以调用不同程序的同一变量
这样就可以调用不同命名空间的相同名字的变量
#include <iostream>
#include <stdlib.h>
int main(void)
{
cout<<"hello world"<<endl;
system("pause");
return 0;
}
这段代码会报错
F:\CODE\C++\train\main.cpp:28|5|error: 'cout' was not declared in this scope|
F:\CODE\C++\train\main.cpp:28|26|error: 'endl' was not declared in this scope|
F:\CODE\C++\train\main.cpp:29|19|error: 'system' was not declared in this scope|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
iostream虽然定义了cout和endl,但是在另外一个命名空间当中,这里是std
格式:using namespace ***
修正后代码如下
#include <iostream>
#include <stdlib.h>
using namespace std; //定义了名字空间
int main(void)
{
cout<<"hello world"<<endl;
system("pause");
return 0;
}
来看一个例子
#include <stdlib.h>
#include <iostream>
using namespace std; //定义了名字空间
namespace A //定义A命名空间
{
int x=1;
void fun()
{
cout<<'A'<<endl;
}
}
namespace B //定义B命名空间
{
int x=2;
void fun()
{
cout<<'B'<<endl;
}
}
int main(void)
{
cout<<A::x<<endl; //A::x就是调用A命名空间下的x变量
B::fun(); //调用B下定义的函数
system("pause");
return 0;
}
最结果输出为
1
B
若在程序中添加
using namespace B
就自动使用B中的变量,即可直接调用 fun():
反之,不定义命名空间 using namespace std
也可以利用 std::endl
的方式直接调用