您的位置:首页 > 其它

自定义string类

2016-01-01 16:18 387 查看
自定义一个简化版本的string类,其中成员函数包括:(1)构造函数。(2)赋值构造函数。(3)赋值操作符(=)。(4)重载操作符([])。(5)比较函数。(6)析构函数。非成员函数只有重载操作符<<(定义为友源函数)。数据成员只有p_str。
MySting();//无参数构造函数
MyString(char *pData);//带参数的构造函数
const char& operator[](unsigned int len)const;//重载[]
char &operator[](unsigned int len);//重载[]
MyString& operator=(const MyString &rhs);//重载=
int compare(const MyString &rhs)const;//比较运算
~MyString();//析构函数
friend ostream& operator<<(ostream & os,MyString &rhs);
自己定义的MyString类,为了简化把声明和定义都放在一个文件中。[code]class MyString
{
public:

//无参数构造函数
MyString()
{
p_str = new char[1];
p_str[0] = '\0';
}

//带参数构造函数
MyString(char *pData)
{
if(pData == NULL)
{
MyString();
}
else
{
int len = strlen(pData);
p_str = new char[len + 1];
for(int i = 0; i < len; ++i)
p_str[i] = pData[i];
p_str[len] = '\0';
}
}

//重载[]接受const常量
const char& operator[](unsigned int len) const
{
if(len > strlen(p_str))
{
len = strlen(p_str);
}
return p_str[len];
}

//重载[]优先接受非const变量
char & operator=(unsigned int len)
{
if(len > strlen(p_str))
{
len = strlen(p_str);
}
return p_str[len];
}

//赋值构造函数
MyString(const MyString &other)
{
int len = strlen(other.p_str);
p_str = new char[len + 1];
for(int i = 0; i < len; ++i)
p_str[i] = other.p_str[i];
p_str[len] = '\0';
}

//赋值运算符重载
//MyString& operator=(const MyString &rhs)
//{
// int len = strlen(rhs.p_str);
// char *tmp = new char[len + 1];
// for(int i = 0; i < len; ++i)
// tmp[i] = rhs.p_str[i];
// tmp[len] = '\0';
// delete p_str;
// p_str = tmp;
// return *this;
//}

//使用copy and swap技术实现赋值运算符
MyString& operator=(const MyString &rhs)
{
if(this != &rhs)
{
MyString tmp(rhs);
char *tp = tmp.p_str;
tmp.p_str = p_str;
p_str = tp;
}
return *this;
}

//比较操作
int compare(const MyString &rhs) const
{
return strcmp(p_str,rhs.p_str);
}

//析构函数
~MyString()
{
delete p_str;
}
//友源函数操作符<<
friend ostream& operator<<(ostream &os,MyString &rhs);

private:
char *p_str;
};

ostream& operator<<(ostream &os,MyString &rhs)
{
return os<<rhs.p_str;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: