// StringClass.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
class CMyString
{
public:
CMyString(char * pData = "denggaoxiang");
CMyString(const CMyString& str);
CMyString& CMyString::operator = (const CMyString & str);
~CMyString();
private:
char * m_ptr;
};
CMyString::CMyString(char *pData)
{
int len = strlen (pData);
if (pData == NULL)
{
if ((m_ptr = new char[1]) != NULL)
{
*m_ptr = '\0';
}
}
else if ((m_ptr = new char [len+1]) != 0)
{
for (int i = 0; i < len ; i ++)
*(m_ptr+i) = *(pData+i);
*(m_ptr+len) = '\0';
}
}
CMyString::CMyString(const CMyString& str)
{
int len = strlen(str.m_ptr);
if ((m_ptr = new char[len + 1]) != NULL)
{
for (int i = 0; i < len; i ++)
{
*(m_ptr+i) = *(str.m_ptr+i);
}
*(m_ptr + len) = '\0';
}
}
CMyString& CMyString::operator = (const CMyString& str)
{
if (this == &str)
return *this;
delete [] m_ptr;
m_ptr = NULL;
int len = strlen(str.m_ptr);
if ((m_ptr = new char [len + 1]) != 0)
{
for (int i = 0; i < len; i ++)
{
*(m_ptr+i) = *(str.m_ptr+i);
}
*(m_ptr + len) = '\0';
}
return *this;
}
CMyString::~CMyString()
{
if (m_ptr != NULL)
{
delete[] m_ptr;
m_ptr = NULL;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
CMyString str("gao");
CMyString str1 = str;
CMyString str2 = str1 = str1;
}
String类
最新推荐文章于 2024-10-28 22:32:17 发布