仿照string类,完成myString 类

- #include
- #include
-
- using namespace std;
- class myString
- {
- private:
- char *str; //记录c风格的字符串
- int size; //记录字符串的实际长度
- public:
- //无参构造
- myString():size(10)
- {
- str = new char[size]; //构造出一个长度为10的字符串
- strcpy(str,""); //赋值为空串
- }
- //有参构造
- myString(const char *s) //string s("hello world")
- {
- size = strlen(s);
- str = new char[size+1];
- strcpy(str, s);
- }
- //拷贝构造
- myString(const myString &other):str(new char(*(other.str))),size(other.size)
- {
- strcpy(this->str,other.str);
- this->size=other.size;
- cout<<"拷贝构造函数"<
- }
- //析构函数
- ~myString()
- {
- delete str;
- cout<<"析构函数:"<<this<
-
- }
- //拷贝赋值函数
- myString & operator=(const myString &other)
- {
- if(this != &other) //确定不是自己给自己赋值
- {
- this->size = other.size;
-
- //判断原来指针空间释放被清空
- if(this->str != NULL)
- {
- delete this->str;
- }
- this->str = new char(*other.str);
-
- }
- cout<<"拷贝赋值函数"<
- return *this; //返回自身引用
- }
- //判空函数
- bool empty()
- {
- return 0==size;
- }
- //size函数
- int mystring_size()
- {
- return strlen(str);
- }
- //c_str函数
- char *c_str()
- {
- return this->str;
- }
- //at函数
- char &at(int pos)
- {
- return str[pos-1];
- }
- //加号运算符重载
- const myString operator+(const myString &R)
- {
- myString c;
- // 计算合并后的字符串长度
- c.size=this->size+R.size;
- // 复制第一个字符串到结果字符串
- memcpy(c.str,this->str,this->size);
- // 复制第二个字符串到结果字符串
- memcpy(c.str+this->size,R.str,R.size+1);
- return c;
- }
- //加等于运算符重载
- myString & operator+=(const myString &R)
- {
- // 复制第二个字符串到第一个字符串后
- memcpy(this->str+this->size,R.str,R.size+1);
- // 计算合并后的字符串长度
- this->size=this->size+R.size;
- return *this;
- }
- //关系运算符重载(>)
- bool operator>(const myString &R)const
- {
- return strcmp(this->str,R.str)>0;
- }
- //中括号运算符重载
- char & operator[](int index)
- {
- return this->str[index];
- }
- };
-
- int main()
- {
-
- myString s1("hello");
- //判空函数
- if(s1.empty())
- {
- cout<<"函数为空"<
- }
- else
- {
- cout<<"函数不为空"<
- }
- //打印s1的长度
- cout<<"size="<
mystring_size()< - //打印s1字符串内容
- cout<<"s1="<
c_str()< - //调用&at函数,打印s1[1]的内容
- cout<<"s1[1]="<
at(2)< - myString s2("world");
- //打印s2字符串内容
- cout<<"s2="<
c_str()< - //调用+=运算符重载函数
- s2+=s1;
- //打印更新之后s2的字符串内容
- cout<<"s2="<
c_str()< - //调用+号运算符重载
- myString s3=s1+s2;
- //打印s3字符串内容
- cout<<"s3="<
c_str()< - //调用[]运算符重载
- cout<<"s3[5]="<
6]< - return 0;
- }
-
相关阅读:
C++ primer 5th笔记
TF-IDF(Term Frequency-Inverse Document Frequency)
LeetCode 87 双周赛
【算法入门&二叉树】从先中后序的遍历到用中后序列构造二叉树|如何抵挡递归法该死的魅力
进军多项式(三):Chirp Z-Transform
powershell美化
华为ACL实验
java精品旅游项目管理系统计算机毕业设计MyBatis+系统+LW文档+源码+调试部署
探索计算机的I/O控制方式:了解DMA控制器的作用与优势
「入门篇」初识JVM (下下) - GC
-
原文地址:https://blog.csdn.net/wdc857/article/details/132817309