对于C++中独有的一种类型,string类型不管在使用还是维护,都特别的方便。那么今天我们就来自定义实现一个string类型。
一:对string类型的成员属性进行确定
其实说白了就是一个动态字符数组。 这里就不多做介绍了,以下代码在vs2019中都跑过没有问题,可以放心使用。
Mstring头文件
#pragma once
#include<iostream>
using namespace std;
class Mstring
{
friend ostream& operator<<(ostream& cout, Mstring& s);
public:
//默认构造
Mstring();
//有参构造
Mstring(const char * str);
//深拷贝构造
Mstring(const Mstring & s);
//对=进行重载
Mstring& operator=(const char* str);
//对=进行重载
Mstring& operator=(const Mstring& s);
//对+进行重载
Mstring operator+(const char* str);
//对+进行重载
Mstring operator+(const Mstring& s);
//对【】进行重载
char& operator[](int index);
//对+=进行重载
void operator+=(const char* str);
//对+=进行重载
void operator+=(const char s);
~Mstring();//析构函数。
private:
char* str;
int m_size;
int m_capacity;
};
//对《《进行重载
ostream& operator<<(ostream& cout, Mstring& s);
Mstring源文件
#define _CRT_SECURE_NO_WARNINGS 1
#include"Mstring.h"
Mstring::Mstring()
{
this->m_size = 0;
this->m_capacity = 10;
this->str = new char[this->m_capacity];
}
Mstring::Mstring(const char* str)
{
int len = strlen(str) + 1;
this->m_capacity = this->m_size = len;
this->str = new char[len];
strcpy(this->str, str);
}
Mstring::Mstring(const Mstring& s)
{
this->m_capacity = s.m_capacity;
this->m_size = s.m_size;
this->str = new char[this->m_capacity];
strcpy(this->str, s.str);
}
Mstring::~Mstring()
{
if (this->str != NULL)
{
delete[] this->str;
this->str = NULL;
}
}
//对《《进行重载
ostream& operator<<(ostream& cout, Mstring& s)
{
cout << s.str;
return cout;
}
//对=进行重载
Mstring& Mstring::operator=(const char* str)
{
if (this->str != NULL)
{
delete[] this->str;
this->str = NULL;
}
this->m_size = this->m_capacity = strlen(str) + 1;
this->str = new char[this->m_size];
strcpy(this->str, str);
return *this;
}
//对=进行重载
Mstring& Mstring::operator=(const Mstring& s)
{
this->m_capacity = s.m_capacity;
this->m_size = s.m_size;
if (this->str != NULL)
{
delete[] this->str;
this->str = NULL;
}
this->str = new char[this->m_capacity];
strcpy(this->str, s.str);
return *this;
}
//对+进行重载
Mstring Mstring::operator+(const char* str)
{
Mstring tmp;
tmp.m_size = this->m_size + strlen(str);
tmp.str = new char[tmp.m_size];
strcpy(tmp.str, this->str);
strcat(tmp.str, str);
return tmp;
}
//对【】进行重载
char& Mstring::operator[](int index)
{
return this->str[index];
}
//对+=进行重载
void Mstring::operator+=(const char* str)
{
Mstring tmp(*this);
if (this->str != NULL)
{
delete[] this->str;
this->str = NULL;
}
this->m_capacity = this->m_size = tmp.m_size + strlen(str);
this->str = new char[this->m_size];
strcpy(this->str, tmp.str);
strcat(this->str, str);
}
//对+=进行重载
void Mstring::operator+=(const char s)
{
Mstring tmp(*this);
delete[]this->str;
this->m_capacity = tmp.m_capacity + 1;
this->m_size = tmp.m_size + 1;
this->str = new char[this->m_size];
strcpy(this->str, tmp.str);
this->str[this->m_size - 2] = s;
this->str[this->m_size - 1] = '\0';
}
当然这里只对使用的比较频繁的运算符进行重载了。