#include <cstddef>
#include <cstring>
using namespace std;
class String
{
public:
String(const char *str = NULL); // 普通构造函数
String(const String &other); // 复制构造函数
~String();
String &operator=(const String &other); // 赋值函数重构"="
String &operator+(const String &other); // 字符串连接函数重构"+"
bool operator==(const String &other); // 判断相等重构 "=="
int getLength(); // 获取长度
private:
char *m_data; // 存放字符串
};
// 普通构造函数
String::String(const char *str)
{
if (str == NULL)
{
m_data = new char[1];
*m_data = '\0'; // 空字符串自动申请内存空间存放结束标志位'\0'
}
else
{
int length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data, str);
}
}
// 析构函数删除m_data空间
String::~String()
{
if (m_data)
{
delete m_data;
m_data = 0;
}
}
// 拷贝函数
String::String(const String &other)
{
if (!other.m_data)
{
m_data = 0;
}
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
}
// 赋值函数
String &String::operator=(const String &other)
{
if (this != &other) // 是否自赋值
{
delete m_data; // 释放原来内存
if (!other.m_data) // 判断other是否为空
{
m_data = 0; // 对m_data作为NULL
}
else
{
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
}
}
return *this;
}
// 字符串连列函数
String &String::operator+(const String &other)
{
String newString;
if (!other.m_data)
{
newString = *this; // other为空时,newString=m_data
}
else if (!m_data)
{
newString = other; // m_data为空,newString=other
}
else
{
newString.m_data = new char[strlen(m_data) + strlen(other.m_data)];
strcpy(newString.m_data, m_data); // 将m_data复制给newString
strcat(newString.m_data, other.m_data); // newString+other
}
return newString;
}
bool String::operator==(const String &other)
{
if (strlen(m_data) != strlen(other.m_data))
{
return false;
}
else
{
return strcmp(m_data, other.m_data) ? false : true;
}
}
int String::getLength()
{
return strlen(m_data);
}
C++String类的实现
1010 views