namespace命名空间的使用
用法 1
#include<iostream> #include<string> namespace China { float population = 14.1; //单位:亿 std::string capital = "北京"; } namespace Japan { float population = 1.27; //单位:亿 std::string capital = "东京"; } using namespace Japan; int main() { std::cout << "首都:" << capital << std::endl; std::cout << "人口:" << population << std::endl; std::cout << "首都:" << China::capital << std::endl; std::cout << "人口:" << China::population << std::endl; system("pause"); return 0; }
用法 2
#include<iostream> #include<string> namespace China { float population = 14.1; //单位:亿 std::string capital = "北京"; } namespace Japan { float population = 1.27; //单位:亿 std::string capital = "东京"; } //注意:没有namspace //直接指定命名空间中的标识符,而不是整个域名 using China::capital; using Japan::population; int main() { std::cout << "首都:" << capital << std::endl; std::cout << "人口:" << population << std::endl; system("pause"); return 0; }
用法 3(错误用法)
#include<iostream> #include<string> namespace China { float population = 14.1; //单位:亿 std::string capital = "北京"; } namespace Japan { float population = 1.27; //单位:亿 std::string capital = "东京"; } using namespace China; using Japan::population; int main() { std::cout << "首都:" << capital << std::endl; std::cout << "人口:" << population << std::endl; //出错 system("pause"); return 0; }
错误原因:
using namespace China; //China命名空间中有population using Japan::population; //又单独声明了Japan中的population
解决方案:
指定完成的域名来表示。
...... int main(){ std::cout << "首都:" << capital << std::endl; std::cout << "人口:" << Japan::population << std::endl; system("pause"); return 0; }