字符串的构造函数、析构函数、拷贝构造函数、赋值操作符

class CString
{
public:
	CString(const char *pStr)
	{
		if (NULL == pStr)
		{
			m_data = new char[1];
			m_data[0] = '\0';
		}
		else
		{
			int len = strlen(pStr);
			m_data = new char [len+1];
			strcpy(m_data, pStr);	// 包括最后的'\0'
		}
	}

	~CString()
	{
		delete [] m_data;
	}

	CString(const CString &other)
	{
		int len = strlen(other.m_data);
		m_data = new char [len+1];
		strcpy(m_data, other.m_data);
	}

	CString& operator=(const CString &other)
	{
		if (this == &other)
		{
			return *this;
		}

		delete [] m_data;

		int len = strlen(other.m_data);
		m_data = new char [len+1];
		strcpy(m_data, other.m_data);

		return *this;
	}

private:
	char *m_data;
};

你可能感兴趣的:(字符串的构造函数、析构函数、拷贝构造函数、赋值操作符)