分享

sizeof的实现

 jijo 2009-11-19
sizeof的实现
jerry 发表于 2008-5-15 15:06:00

0
//关于模拟sizeof函数实现计算类型大小
//查了很多资料,也用过模板
//但都无法获得对象的类型
//下面是一个用宏来实现的方法
#define my_sizeof(L_Value) (                    \
    (char *)(&L_Value + 1) - (char *)&L_Value   \
)

#i nclude <stdio.h>
#i nclude <stdio.h>
int main(void){
    int i;
    double f;
    double a[4];
    double *p;

    printf("%d\n", my_sizeof(i));
    printf("%d\n", my_sizeof(f));
    printf("%d\n", my_sizeof(a));
    printf("%d\n", my_sizeof(p));
    printf("%d\n", my_sizeof("abdegh"));

    return 0;
}

//模板的类型操作
#i nclude<iostream>

using namespace std;

template<class Any>
int LengthOfArray(Any * p)
{
   return int(p+1) - int(p);
}

int main()
{
   double * q;
   char a[10];

   cout << LengthOfArray(q)<<endl;
   cout << LengthOfArray(&a)<<endl;
  
   return 0;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多