C++中自定义string类的实现
mystring.h头文件
#ifndef MYSTRING_H
#define MYSTRING_H
#include <ostream>
#include <cstring>
using namespace std;
class MyString
{
public:
MyString();
MyString(const char *str);
MyString(const MyString &other);
MyString &operator=(const char *str);
MyString &operator=(const MyString &other);
MyString &operator+(const MyString &other);
size_t myLen();
friend ostream &operator<<(ostream &output,const MyString &str);
char &operator[](int a);
~MyString();
private:
char *m_pString;
};
#endif
mystring.c
#include "mystring.h"
#include <iostream>
MyString::MyString()
{
int length = 0;
m_pString = new char[length + 1];
strcpy(m_pString,"");
}
MyString::MyString(const char *str)
{
if(str == nullptr)
{
int length = 0;
m_pString = new char[length + 1];
strcpy(m_pString,"");
}
else {
size_t length = strlen(str);
m_pString = new char[length + 1];
strcpy(m_pString,str);
}
}
MyString::MyString(const MyString &other)
{
if(this->m_pString != nullptr)
{
delete [] this->m_pString;
this->m_pString = nullptr;
}
size_t length = strlen(other.m_pString);
this->m_pString = new char[length + 1];
strcpy(this->m_pString,other.m_pString);
}
MyString &MyString::operator=(const char *str)
{
if(this->m_pString != nullptr)
{
delete [] this->m_pString;
this->m_pString = nullptr;
}
size_t length = strlen(str);
this->m_pString = new char[length + 1];
strcpy(this->m_pString,str);
return *this;
}
MyString &MyString::operator=(const MyString &other)
{
if(this->m_pString != nullptr)
{
delete [] this->m_pString;
this->m_pString = nullptr;
}
size_t length = strlen(other.m_pString);
this->m_pString = new char[length + 1];
strcpy(this->m_pString,other.m_pString);
return *this;
}
MyString &MyString::operator+(const MyString &other)
{
MyString *pStrTemp = new MyString;
pStrTemp->m_pString = new char[strlen(this->m_pString) + strlen(other.m_pString) + 1];
strcpy(pStrTemp->m_pString,this->m_pString);
strcat(pStrTemp->m_pString,other.m_pString);
return *pStrTemp;
}
size_t MyString::myLen()
{
return strlen(this->m_pString);
}
ostream &operator<<(ostream &output, const MyString &str)
{
output << str.m_pString << endl;
return output;
}
char &MyString::operator[](int a)
{
return this->m_pString[a];
}
MyString::~MyString()
{
if(m_pString != nullptr)
{
delete [] m_pString;
}
m_pString = nullptr;
}
测试程序
#include "mystring.h"
#include <iostream>
using namespace std;
int main()
{
MyString s1;
cout << "s1:" << s1;
MyString s2("Hello");
cout << "s2:" << s2;
s1 = "World";
MyString s3(s1);
cout << "s3:" << s3;
MyString s4;
s4 = s2 + " " + s3 + "!";
cout << "s4:" << s4;
cout << "s4[1]:" << s4[1] << endl;
cout << "len of s4:" << s4.myLen();
return 0;
}