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 2022-10-10 17:20 会飞的鱼-blog 阅读(7) 评论(0) 编辑 收藏 举报 来源
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现