小伙伴们或许会对C++程序中都要添加using namespace std;感到疑惑。原因在于几乎每个函数都会使用cout,因此需要能够访问位于名称空间std中的cout定义。
看看下面2个带有函数的程序:
//在英国,很多浴室中的体重称都以英石(stone)为单位,不像美国以磅或公斤为单位。一英石等于14磅,请使用一个函数来完成这样的转换。
#include <iostream>
int stonetolb(int);
int main()
{
using namespace std;
int stone;
cout << "Enter the weight in stone:";
cin >> stone;
int pounds = stonetolb(stone);
cout << stone << "stone = ";
cout << pounds << "pounds." << endl;
return 0;
}
int stonetolb(int sts)
{
return 14 * sts;
}
#include <iostream>
using namespace std;
void po(int);
int main()
{
po(3);
}
void po(int n)
{
cout << "po为" << n << endl;
}
是否很奇怪两个函数中using namespace std; 放置的位置不一样呢?其实,名称空间也有其通行的理念,那就是只让需要访问名称空间std的函数stonetolb()能够访问名称空间std。因此编译指令using被放在函数main()中,使得只有该函数能够访问名称空间std。
总而言之,让程序能够访问名称空间std的方法有很多种,现在给小伙伴们分享其中4种:
(1)将using namespace std;放在函数定义之前,让文件中所有的函数都能够使用名称空间std中所有的元素;
(2)将using namespace std;放在特定的函数定义中,让该函数能够使用名称空间std中的所有元素;
(3)在特定的函数中使用类似using std::cout; 这样的编译指令,而不是using namespace std;,让该函数能够使用指定的元素,如cout,cin;
(4)完全不使用编译指令using,而在需要使用名称空间std中的元素时,使用前缀std:: ,如下:
std::cout<<"I am using cout and endl from the std namespace"<<std::endl;
番外篇(一)就到这里啦!相信这篇博客能为不少的小伙伴解决为什么要加上using namespace std;的疑惑。其实命名空间有很多种,我也将在不久的将来分享给大家。很感激能看到这里的你,希望你能点动你的小拇指给施律.一点小小的支持与关注!