Chinaunix首页 | 论坛 | 博客
  • 博客访问: 828153
  • 博文数量: 190
  • 博客积分: 2991
  • 博客等级: 少校
  • 技术积分: 2400
  • 用 户 组: 普通用户
  • 注册时间: 2012-09-24 18:11
文章分类

全部博文(190)

文章存档

2015年(3)

2014年(1)

2013年(65)

2012年(121)

我的朋友

分类: C/C++

2012-10-10 07:31:02

在C语言中,void类型是没有问题,代码如下:main.c
[cpp] view plaincopy
#include  
#include  
#define GENERIC  
void *MyStrcpy( void *dst, const void GENERIC *src, unsigned int len )  
{  
    unsigned char *pDst;  
    const unsigned char GENERIC *pSrc;  
      
    pSrc = src;  
    pDst = dst;  
      
    while ( len-- )  
        *pDst++ = *pSrc++;  
      
    return ( pDst );  
}  
void main()  
{  
    int i=1;  
    int j=2;  
    char d[]="123";  
    char s[]="123456789";  
    char d1[]="123";  
    char s1[]="123456789";  
      
  
    strcpy(d,s);  
    printf("s=%s   d=%s\n",s,d);  
    MyStrcpy(d1,s1,3);  
    printf("d1=%s   s1=%s\n",s1,d1);   
    printf("i=0X%08X\nj=0X%08X\ns=0X%08X\nd=0X%08X\ns1=0X%08X\nd1=0X%08X\nstrcpy=0X%08X\nprintf=0X%08X\n",&i,&j,s,d,s1,d1,strcpy,printf);  
}  
而在C++中,我们要改成模板,代码如下:main.cpp
[cpp] view plaincopy
#include  
#include  
#define GENERIC  
template  
void *MyStrcpy( T *dst, const T GENERIC *src, unsigned int len )  
{  
    T *pDst;  
    const T GENERIC *pSrc;  
      
    pSrc = src;  
    pDst = dst;  
      
    while ( len-- )  
        *pDst++ = *pSrc++;  
      
    return ( pDst );  
}  
void main()  
{  
    int i=0,j=1;  
    char s[]="123456789";  
    char d[]="123";  
    char s1[]="123456789";  
    char d1[]="123";  
    strcpy(d,s);  
    printf("s=%s   d=%s\n",s,d);  
    MyStrcpy(d1,s1,3);  
    printf("d1=%s   s1=%s\n",s1,d1);   
    printf("i=0X%08X\nj=0X%08X\ns=0X%08X\nd=0X%08X\ns1=0X%08X\nd1=0X%08X\nstrcpy=0X%08X\nprintf=0X%08X\n",&i,&j,s,d,s1,d1,strcpy,printf);  
}  
 
以上代码的功能是一样的,但是我们要进行不同的改变。上面是在VC++6.0编译环境下测试。
原文地址:
阅读(799) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~