在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编译环境下测试。
原文地址:
阅读(830) | 评论(0) | 转发(0) |