C++实现简单的String类
最后更新于:2022-04-01 20:13:52
~~~
#include "stdafx.h"
#include
#include
// 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 = "\0";
}
else
{
// strlen(str)是计算字符串的长度,不包括字符串末尾的“\0”
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 = "\0";
}
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 = "\0";
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("\nDestory``````");
}
int main()
{
// 调用普通构造函数
String* str = new String("PWRD");
str->printValue();
delete str;
// 调用赋值函数
String newStr = "CDPWRD";
printf("\n%s\n", newStr);
String copyStr = String(newStr);
copyStr.printValue();
system("pause");
return 0;
}
~~~
调试结果:
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-19_57b6ce7f0ab94.jpg)
';