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 2022-10-10 17:20  会飞的鱼-blog  阅读(12)  评论(0)    收藏  举报  来源

导航