首页 技术 正文
技术 2022年11月23日
0 收藏 715 点赞 3,446 浏览 1127 个字

c++ anonymous namespace — 匿名空间

匿名空间,匿名类,匿名联合体,匿名结构体。 匿名空间

 

  1. #include <stdio.h>
  2. namespace A {
  3. int ID = 1;
  4. }
  5. namespace {
  6. int ID = 11;
  7. }
  8. namespace B {
  9. int ID = 21;
  10. }
  11. int main(void){
  12. printf(“ID %d \n”,ID);
  13. }

输出

  1. ID 11

这里用到是C的函数,减少std空间的干扰。这里输出的是匿名空间的内容。那么就类似于如下用法

  1. namespace __UNIQUE_NAME_ {
  2. int ID;
  3. }
  4. using namespace __UNIQUE_NAME_;

如果修改代码如下

  1. #include <stdio.h>
  2. namespace A {
  3. int ID = 1;
  4. }
  5. namespace {
  6. int ID = 11;
  7. }
  8. namespace B {
  9. int ID = 21;
  10. }
  11. namespace {
  12. int ID = 41;
  13. }
  14. int main(void){
  15. printf(“ID %d \n”,ID);
  16. }

编译报错,如下

  1. t_anonymity_space.cpp:14: error: redefinition of ‘int ::ID’
  2. t_anonymity_space.cpp:7: error: ‘int ::ID’ previously defined here

在不同的文件中呢

  1. //file def.h
  2. namespace {
  3. int ID = 41;
  4. }
  1. #include <stdio.h>
  2. #include “def.h”
  3. namespace A {
  4. int ID = 1;
  5. }
  6. namespace {
  7. int ID = 11;
  8. }
  9. namespace B {
  10. int ID = 21;
  11. }
  12. int main(void){
  13. printf(“ID %d \n”,ID);
  14. }

编译报错

  1. t_anonymity_space.cpp:7: error: redefinition of ‘int ::ID’
  2. def.h:3: error: ‘int ::ID’ previously defined here

这里说明匿名namespace是在一个空间里。 引用其他空间以后的用法

  1. #include <stdio.h>
  2. namespace A {
  3. int ID = 1;
  4. }
  5. namespace {
  6. int ID = 11;
  7. int id = 12;
  8. }
  9. namespace B {
  10. int ID = 21;
  11. }
  12. int main(void){
  13. printf(“ID %d \n”,ID);
  14. using namespace A;
  15. printf(“ID %d – %d – %d \n”,A::ID, ::ID, id);
  16. }

输出

  1. ID 11
  2. ID 1 – 11 – 12

引用了其他空间,并且此时此时如果使用 匿名空间都是在同一个空间,并且同名的必须加上::加以区分。我在这里猜测一下,全局变量是不是就是在默认的匿名空间的呢?从现象来看,八成是。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,960
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,484
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,330
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,113
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,745
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,779