fqy131314

C++(命名空间的使用小结)

C++避免名字冲突:使用命名空间

用法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(void) {

      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 = "东京";

}

//注意:没有namespace

//直接指定命名空间中的标识符,而不是整个域名

using China::capital;

using Japan::population;

int main(void) {

      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(void) {

      std::cout << "首都:" << capital << std::endl;

      std::cout << "人口:" << population << std::endl; //出错!

      system("pause");

      return 0;

}

错误提示:

population”:不明确的符号

错误原因:

解决方案:

指定完整的域名(Japan::population )来表示。

......

int main(void) {

      std::cout << "首都:" << capital << std::endl;

      std::cout << "人口:" << Japan::population << std::endl; //出错!

      system("pause");

      return 0;

}

 

posted on   会飞的鱼-blog  阅读(7)  评论(0编辑  收藏  举报  

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示