1.仿照string类,完成mystring类
- #include
- #include
-
- using namespace std;
-
- class mystring
- {
- private:
- char *str;
- int size;
- public:
- //无参构造
- mystring():size(10)
- {
- str = new char[size];
- strcpy(str,"");
- cout<<"无参构造"<
- }
-
- //有参构造
- mystring(const char *s)
- {
- size = strlen(s);
- str = new char[size+1];
- strcpy(str,s);
- cout<<"有参构造"<
- }
-
- //拷贝构造
- mystring(const mystring &other)
- {
- this->size=other.size;
- this->str=new char[this->size];
- strcpy(this->str,other.str);
-
- cout<<"拷贝构造"<
- }
-
- //析构函数
- ~mystring()
- {
- delete []str;
- cout<<"mystring::析构函数"<<this<
- }
-
- //拷贝赋值函数
- mystring & operator=(const mystring &other)
- {
- if(this != &other)
- {
- strcpy(this->str,other.str);
- this->size=other.size;
-
- //判断原来指针空间释放被清空
- if(this->str !=NULL)
- {
- delete this->str;
- }
- this->str=new char(*other.str);
- }
- cout<<"mystring::拷贝赋值函数"<
- return *this;
- }
-
- //判空函数
- bool str_empty()
- {
- return (this->size==0);
- }
-
- //size函数
- int str_size()
- {
- return strlen(this->str);
- }
-
- //c_str函数
- char *myc_str()
- {
- return str;
- }
-
-
- //at函数
- char &at(int pos)
- {
- return *(this->str+pos-1);
- }
-
- //加号运算符重载
- mystring operator+(const mystring &r)const
- {
- mystring s1;
- strcat(s1.str,this->str);
- strcat(s1.str,r.str);
- s1.size=this->size+r.size;
- return s1;
- }
-
-
- //加等于运算符重载
- mystring* operator+=(const mystring&r)
- {
- strcat(this->str,r.str);
- this->size+=r.size;
- return this;
- }
-
- //关系运算符重载(>)
- bool operator>(const char* &r)const
- {
- if(strcmp(this->str,r)<=0)
- {
- return 0;
- }
- return 1;
- }
-
- //中括号运算符重载
- char &operator[](int index)const
- {
- return this->str[index-1];
- }
-
- friend void show(const mystring str);
- };
-
- void show(const mystring s)
- {
- cout<
- cout<<"size = "<
- }
-
- int main()
- {
- mystring s("lamia");
- show(s);
- mystring s2("selane");
- show(s2);
- mystring s3=s2;
- show(s3);
- mystring s4=s+s2;
- show(s4);
- s2+=s;
- show(s2);
-
- return 0;
- }
-
相关阅读:
MapStruct简单入门
信息系统项目管理师必背核心考点(五十六)配置控制委员会(CCB)的工作
OceanBase Oracle 模式下系统视图权限导致的故障一例
taro小程序开发、h5前端开发有什么不一样呢?
多次声称不造车的华为,如今正在借别人的手造自己的车?
Syntax Error: Error: Missing binary. See message above.
一键生成大学、专业甚至录取概率,AI填报志愿卡这么神奇?
JavaWeb三大组件之Listener------Listener详细讲解
前后端分离项目,vue+uni-app+php+mysql电影院售票系统(H5移动项目) 开题报告
基于FPGA的 图像边沿检测
-
原文地址:https://blog.csdn.net/2201_75732711/article/details/132817361