实现一个string类的简单实现
class CStr
{
public:
CStr();
~CStr();
CStr(const char* str);
CStr(const CStr& cstr);
CStr& operator=(const CStr& cstr); //重载=运算符
CStr& operator+=(const CStr& cstr); //重载+=运算符
CStr& operator=(const char* str); //重载=运算符
CStr& operator+=(const char* str); //重载+=运算符
const CStr operator+(const CStr& cstr); //重载+运算符
const CStr operator+(const char* str); //重载+运算符
operator const char*(); //括号运算符重载
//友元函数
friend std::ostream& operator<<(std::ostream &out, const CStr &cstr);
private:
char* m_str;
};
CStr::CStr()
{
m_str = NULL;
}
CStr::~CStr()
{
if (m_str)
{
free(m_str);
}
m_str = NULL;
}
CStr::CStr(const char* str)
{
m_str = strdup(str);
}
CStr::CStr(const CStr& cstr)
{
m_str = strdup(cstr.m_str);
}
CStr& CStr::operator=(const CStr& cstr)
{
return (*this = cstr.m_str);
}
CStr& CStr::operator+=(const CStr& cstr)
{
return (*this += cstr.m_str);
}
CStr& CStr::operator=(const char* str)
{
if (m_str)
{
free(m_str);
m_str = NULL;
}
m_str = strdup(str);
return *this;
}
CStr& CStr::operator+=(const char* str)
{
return *this = *this + str;
}
const CStr CStr::operator+(const CStr& cstr)
{
int nlen = strlen(m_str);
nlen += strlen(cstr.m_str);
CStr str;
str.m_str = (char *)malloc(nlen + 1);
strcpy(str.m_str, m_str);
strcat(str.m_str, cstr.m_str);
return str;
}
const CStr CStr::operator+(const char* pstr)
{
int nlen = strlen(m_str);
nlen += strlen(pstr);
CStr str;
str.m_str = (char *)malloc(nlen + 1);
strcpy(str.m_str, m_str);
strcat(str.m_str, pstr);
return str;
}
CStr::operator const char*()
{
return m_str;
}
std::ostream& operator<<(std::ostream &out, const CStr &cstr)
{
out << cstr.m_str;
return out;
}