string是c++的标准类库的一个字符串类,也称c++的字符串,有空的话自己实现这个类挺有意思的,当然这个类的功能是相当的强大,这里只是写了九牛一毛而已。
//sstring.h
#include <iostream>
using namespace std;
class SString
{
public:
SString(const char *pSz=NULL); //构造函数
SString(SString &str); //复制构造
~SString(void);
SString& operator=(const SString &str); //赋值运算符
bool operator==(const SString &str); //相等运算符
SString& operator+(const SString &str); //字符串相连
friend ostream &operator<<(ostream &cout, const SString &str); // 输出流
private:
char *m_pCh;
};
//sstring.cpp
#include "SString.h"
#include <string.h>
SString::SString( const char *pSz /*= NULL*/)
{
if(NULL == pSz)
{
m_pCh = new char[1];
*m_pCh = '\0';
}
else
{
m_pCh = new char[strlen(pSz)+1];
if(NULL != m_pCh)
{
strcpy(m_pCh, pSz);
}
}
}
SString::SString( SString &str )
{
m_pCh = new char[strlen(str.m_pCh)+1];
strcpy(m_pCh, str.m_pCh);
}
SString::~SString(void)
{
if(NULL != m_pCh)
{
delete []m_pCh;
}
}
SString& SString::operator=( const SString &str )
{
if(this == &str)
{
return *this;
}
if(NULL != m_pCh)
{
delete m_pCh;
}
m_pCh = new char[strlen(str.m_pCh)+1];
if(this != &str)
{
strcpy(m_pCh, str.m_pCh);
}
return *this;
}
bool SString::operator==( const SString &str )
{
if(this == &str)
{
return true;
}
return false;
}
SString& SString::operator+( const SString &str )
{
char *pTmp = new char[strlen(m_pCh)+1];
strcpy(pTmp, m_pCh);
delete []m_pCh;
m_pCh = new char[strlen(pTmp) + strlen(str.m_pCh) + 1];
strcpy(m_pCh, pTmp);
strcat(m_pCh, str.m_pCh);
return *this;
}
SString SString::operator++( int )
{
SString tmp =*this;
++(*this);
return SString(tmp);
}
上面的实现不难,相信大家都会,但有很多的细节需要注意的,比方说拷贝构造函数的参数为什么要用引用类型?是为了省去传值时不执行形参的拷贝吗?如果不是,那直接用类型可以吗,为什么, 用指针可以吗?