自定义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;
}
相关文章推荐
- SQL Server Convert()函数
- 域名301跳转
- A Curious Matt
- MySQL GTID模式 主从复制跳过错误事务
- 转入中国国家顶级域名需要哪些手续?
- LINUX下编译c++11的代码
- Jeecg社区wiki在开放,最终能够在线看文档啦!!!
- 一个命令禁止恢复Win10硬盘已删文件的技巧
- Linux终端切换和ls、cd、date、shutdown相关命令
- Atmel 官方网站中文版
- leetcode之House Robber
- 中国企业可以注册的域名有哪些?
- n*n(n<20,为正奇数)阶方阵(题型二)
- Android5.1中联系人新建和保存机制
- Context中有一个startActivity方法
- NSURLConnection — POST请求
- 第一篇 linux中红黑树的具体实现及迁移,应用
- STM32之中断与事件---中断与事件的区别
- BitSet构造函数的两种特例
- 静态成员数据和静态成员函数