牛骨文教育服务平台(让学习变的简单)
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>

// delete之后将指针置为NULL防止空指针
#define SAFE_DELETE(p) do{ if(p){delete(p);  (p)=NULL;} }while(false);

class String
{
public:
	// 普通构造函数
	String(const char *str = NULL);
	// 拷贝构造函数
	String(const String &other);
	// 赋值函数(重载操作符=)
	String & operator = (const String &other);
	// 析构函数
	~String();

	void printValue(){ printf("%s", m_pcData); };

private:
	// 保存字符串的指针
	char* m_pcData;
};

String::String(const char *str)
{
	if (str == NULL)
	{
		m_pcData = new char[1];
		m_pcData = "";
	}
	else
	{
		// strlen(str)是计算字符串的长度,不包括字符串末尾的“”
		size_t len = strlen(str) + 1;
		m_pcData = new char[len];
		strcpy_s(m_pcData, len, str);
	}
}

String::String(const String& other)
{
	if (other.m_pcData == NULL)
	{
		m_pcData = "";
	}
	else
	{
		int len = strlen(other.m_pcData) + 1;
		m_pcData = new char[len];
		strcpy_s(m_pcData, len, other.m_pcData);
	}
}

String& String::operator = (const String &other)
{
	// 如果是自身就直接返回了
	if (this == &other)
		return *this;
	// 判断对象里面的值是否为空
	if (other.m_pcData == NULL)
	{
		delete m_pcData;
		m_pcData = "";
		return *this;
	}
	else
	{
		// 删除原有数据
		delete m_pcData;
		int len = strlen(other.m_pcData) + 1;
		m_pcData = new char[len];
		strcpy_s(m_pcData, len, other.m_pcData);
		return *this;
	}
}

String::~String()
{
	SAFE_DELETE(m_pcData);
	printf("
Destory``````");
}

int main()
{
	// 调用普通构造函数
	String* str = new String("PWRD");
	str->printValue();
	delete str;
	// 调用赋值函数
	String newStr = "CDPWRD";
	printf("
%s
", newStr);
	String copyStr = String(newStr);
	copyStr.printValue();
	system("pause");
	return 0;
}

调试结果: