仿照string类,完成myString 类
#include <iostream>
#include<cstring>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<<"拷贝构造函数"<<endl;}//析构函数~myString(){delete str;cout<<"析构函数:"<<this<<endl;}//拷贝赋值函数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<<"拷贝赋值函数"<<endl;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<<"函数为空"<<endl;}else{cout<<"函数不为空"<<endl;}//打印s1的长度cout<<"size="<<s1.mystring_size()<<endl;//打印s1字符串内容cout<<"s1="<<s1.c_str()<<endl;//调用&at函数,打印s1[1]的内容cout<<"s1[1]="<<s1.at(2)<<endl;myString s2("world");//打印s2字符串内容cout<<"s2="<<s2.c_str()<<endl;//调用+=运算符重载函数s2+=s1;//打印更新之后s2的字符串内容cout<<"s2="<<s2.c_str()<<endl;//调用+号运算符重载myString s3=s1+s2;//打印s3字符串内容cout<<"s3="<<s3.c_str()<<endl;//调用[]运算符重载cout<<"s3[5]="<<s3[6]<<endl;return 0;
}