赋值运算符的重载
#include<stdio.h>
#include<stdlib.h>#include<string.h>
class A{
private:
char *p;
public:
A operator=(const A &a)
{
free(p);
p=NULL;
p=(char *)malloc(strlen(a.p)+1);
strcpy(p,a.p);
return *this;
}
A(const A &a)
{
p=(char *)malloc(strlen(a.p)+1);
strcpy(p,a.p);
}
A(char *p1=NULL)
{
p=(char *)malloc(strlen(p1)+1);
strcpy(p,p1);
}
char *getP()
{
return p;
}
~A()
{
if(p!=NULL)
{
free(p);
p=NULL;
}
}
};
void main()
{
char s[]="abc";
char s1[]="abcd";
A myA(s);
A myB=myA;
A myC(s1);
myA=myC;
printf("%s %s %s\n",myA.getP(),myB.getP(),myC.getP());
}