/*lesson 2*/
#include <iostream> //头文件☆文件后无需添加.h
#include <string> //C++ 字符串头文件
using namespace std; //可在string\cout\cin前面无需添加std 使用名称命名空间
namespace China {
float pipulation = 14.1; //人口数量
string capital = "北京"; //首都
}
namespace Japan {
float pipulation = 1.27; //人口数量
string capital = "东京"; //首都
}
int main()
{
//以下内容2选1
/*using namespace China;
cout << "默认中国选项:首都" << capital << " 人口" << pipulation << "亿人." << endl; */
using Japan::capital;
cout << "默认将首都设为日本" << capital << endl;
cout << "China首都:" << China::capital << " 人口" << China::pipulation << "亿人." << endl;
cout << "Japan首都:" << Japan::capital << " 人口" << Japan::pipulation << "亿人." << endl;
cout << endl; //换行
system("pause"); //程序暂停
return 0;
}
运行结果:
第1个:

第2个:

这段代码展示了如何在C++中使用命名空间来存储不同国家的人口和首都信息。程序首先定义了China和Japan两个命名空间,分别包含相应国家的人口和首都。在main函数中,通过using关键字选择显示日本的首都,并随后输出了China和Japan两国的首都及人口信息。

被折叠的 条评论
为什么被折叠?



