最近在看一些C++的资料~~看到有讲拷贝函数的写法,觉得听好玩儿的就写了出来,当作记录分享出来。
- 函数内用临时变量来接受形参,使得原有形参不受函数内部的改变。(不要轻易改掉形参的值)
- 注意函数内部的指针判空。
#include <iostream>
using namespace std;
char *MyStrCpy1(char *strDest, const char *strSrc)
{
char *tempStrDest = strDest ;
const char *tempStrSrc = strSrc ;
if ( tempStrDest == NULL || tempStrSrc == NULL)
{
return NULL ;
}
if ( tempStrDest == tempStrSrc)
{
return tempStrDest ;
}
for(; *tempStrSrc!='\0'; ++tempStrDest,++tempStrSrc)
{
*tempStrDest = *tempStrSrc;
}
*tempStrDest='\0';
return strDest ;
}
char *MyStrCpy2(char *strDest, const char *strSrc)
{
char *tempStrDest = strDest ;
const char *tempStrSrc = strSrc ;
if ( tempStrDest == NULL || tempStrSrc == NULL)
{
return NULL ;
}
if ( tempStrDest == tempStrSrc)
{
return tempStrDest ;
}
while( (*tempStrDest++ = *tempStrSrc++) !='\0') ;
return strDest ;
}
char *MyStrCpy3(char *strDest, const char *strSrc)
{
char *tempStrDest = strDest ;
const char *tempStrSrc = strSrc ;
if ( tempStrDest == NULL || tempStrSrc == NULL)
{
return NULL ;
}
if ( tempStrDest == tempStrSrc)
{
return tempStrDest ;
}
while( (*tempStrDest++ = *tempStrSrc++)) ;
return strDest ;
}
int main()
{
char myString[]="HELLO CSDN ,人间词话·CODE";
char temp1[100];
char temp2[100];
char temp3[100];
cout<<MyStrCpy1(temp1,myString)<<endl;
cout<<MyStrCpy2(temp2,myString)<<endl;
cout<<MyStrCpy3(temp3,myString)<<endl;
}