赋值运算符重载
//赋值运算符重载
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class CMyString
{
public:
CMyString(char* pData = NULL);
CMyString(const CMyString& str);
~CMyString(void);
CMyString& operator = (const CMyString& str);
friend ostream& operator << (ostream & stream,const CMyString str)
{
return stream<<str.m_pData<<endl;
}
private:
char* m_pData;
};
CMyString::CMyString(char* pData)
{
m_pData = new char[strlen(pData)+1];
strcpy(m_pData,pData);
}
CMyString::CMyString(const CMyString& str)
{
m_pData = new char[strlen(str.m_pData)+1];
strcpy(m_pData,str.m_pData);
}
CMyString::~CMyString(void)
{
delete [] m_pData;
m_pData = NULL;
}
CMyString& CMyString::operator = (const CMyString& str)
{
if(this != &str)
{
CMyString strtmp(str);
char* ptmp = strtmp.m_pData;
strtmp.m_pData = this->m_pData;
this->m_pData = ptmp;
}
return *this;
}
int main()
{
CMyString str("helloworld");
CMyString str2(str);
CMyString str3 = str;
cout<<str<<str2<<str3;
return 0;
}