#include <iostream>
using namespace std;
class Name
{
public:
Name(const char *myp)
{
m_len = strlen(myp);
//m_p =(char *)malloc(m_len+1);
m_p = new char[m_len + 1];
strcpy(m_p,myp);
}
Name(const Name& obj)
{
m_len = obj.m_len;
//m_p = (char*)malloc(m_len+1);
m_p = new char[m_len + 1];
strcpy(m_p,obj.m_p);
}
~Name()
{
if (m_p!=NULL)
{
//free(m_p);
delete[] m_p;
m_p = NULL;
m_len =0;
}
}
void print()
{
cout<<"m_p:"<<this->m_p<<endl;
}
//成员函数方法实现=
Name& operator=(const Name &obj)
{
if (this->m_p!=NULL)
{
//free(this->m_p);
delete[] this->m_p;
this->m_p = NULL;
this->m_len = 0;
}
this->m_len = obj.m_len;
//this->m_p = (char *)malloc(m_len+1);
this->m_p = new char[m_len+1];
strcpy(this->m_p,obj.m_p);
return *this;
}
protected:
private:
int m_len;
char * m_p;
};
int main()
{
Name obj("abcd");
Name obj2("efgh");
Name obj3("lkmnf");
obj = obj2 = obj3;//程序出错 浅拷贝 解决重载=操作符 实现深拷贝
obj.print();
system("pause");
return 0;
}