头文件
#ifndef MY_STRING_H
#define MY_STRING_H
class Mstring
{
private:
int m_length;
char* m_pointer;
public:
Mstring();
Mstring(const char* str);
Mstring(const Mstring& obj);
int length()const;
const char* c_str();
char& operator[](int index)const;
Mstring& operator = (const Mstring& obj);
const Mstring operator + (const Mstring& obj)const;
bool operator > (const Mstring& obj)const;
bool operator < (const Mstring& obj)const;
const Mstring& operator += (const Mstring& obj);
bool operator == (const Mstring& obj)const;
bool operator != (const Mstring& obj)const;
Mstring& self();
~Mstring();
};
#endif
函数实现
#include "My_string.h"
#include <cstring>
Mstring::Mstring():m_length(10)
{
m_pointer = new char[m_length];
strcpy(m_pointer, "");
}
Mstring::Mstring(const char* str)
{
m_length = strlen(str);
m_pointer = new char[m_length];
strcpy(m_pointer, str);
}
Mstring::Mstring(const Mstring& obj)
{
m_length = obj.m_length;
m_pointer = new char[m_length];
memcpy(m_pointer, obj.m_pointer, m_length);
}
int Mstring::length()const
{
return m_length;
}
char& Mstring::operator[](int index)const
{
return m_pointer[index];
}
const char* Mstring::c_str()
{
return m_pointer;
}
Mstring& Mstring::operator = (const Mstring& obj)
{
if(this != &obj)
{
char* pointer = new char[obj.m_length];
if( pointer )
{
memcpy(pointer, obj.m_pointer, obj.m_length);
m_length = obj.m_length;
delete m_pointer;
m_pointer = pointer;
}
}
return *this;
}
const Mstring Mstring::operator + (const Mstring& obj)const
{
Mstring ret;
delete ret.m_pointer;
ret.m_length = m_length + obj.m_length;
ret.m_pointer = new char[ret.m_length];
if( ret.m_pointer )
{
strcpy(ret.m_pointer, m_pointer);
strcat(ret.m_pointer, obj.m_pointer);
}
return ret;
}
bool Mstring::operator > (const Mstring& obj)const
{
return (strcmp(m_pointer, obj.m_pointer) > 0) ? 1 : 0;
}
bool Mstring::operator < (const Mstring& obj)const
{
return (strcmp(m_pointer, obj.m_pointer) < 0) ? 1 : 0;
}
const Mstring& Mstring::operator += (const Mstring& obj)
{
char* pointer = new char[m_length + obj.m_length];
if( pointer )
{
strcpy(pointer, m_pointer);
strcat(pointer, obj.m_pointer);
m_length = m_length + obj.m_length;
delete m_pointer;
m_pointer = pointer;
}
return *this;
}
bool Mstring::operator == (const Mstring& obj)const
{
return (strcmp(m_pointer, obj.m_pointer) == 0) ? 1 : 0;
}
bool Mstring::operator != (const Mstring& obj)const
{
return (strcmp(m_pointer, obj.m_pointer) != 0) ? 1 : 0;
}
Mstring& Mstring::self()
{
return *this;
}
Mstring::~Mstring()
{
delete[]m_pointer;
}
效果图