当前位置: 首页 > news >正文

C++ Day4

目录

仿照string类,完成myString 类

思维导图


仿照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,"");         //赋值为空串cout<<"无参构造"<<endl;}//有参构造myString(const char *s)          //string  s("hello world"){size = strlen(s);str = new char[size+1];strcpy(str, s);cout<<"有参构造"<<endl;}//拷贝构造myString(const myString &other){this->str=new char[other.size+1];strcpy(str,other.str);this->size=other.size;cout<<"拷贝构造"<<endl;}//析构函数~myString(){delete str;cout<<"析构函数"<<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.size+1];strcpy(str,other.str);cout<<"拷贝赋值"<<endl;}return *this;}//判空函数bool empty(){return 0==size;}//size函数int my_size(){cout<<strlen(str)<<endl;return strlen(str);}//c_str函数char * my_c_str(){return str;}//at函数char &at(int pos){return str[pos];}//加号运算符重载const myString operator+(const myString &other)const{myString c;c.str=new char[size+other.size];strcpy(c.str,str);strcat(c.str,other.str);c.size=size+other.size;return c;}//加等于运算符重载myString &operator+=(const myString &other){strcat(str,other.str);size+=other.size;return *this;}//关系运算符重载(>)bool operator>(const myString &other)const{if(strcmp(str,other.str)>0){return true;}return false;}//中括号运算符重载char & operator[](int i){if(i >= 0 && i< size){return this->str[i];}else{cout<<"数组越界"<<endl;}}void show(){cout<<str<<endl;}
};int main()
{char arr[10]="hello";myString s1(arr);  //有参构造myString s2=s1;   //拷贝构造myString s3;   //无参构造s3=s2;    //拷贝赋值函数s1.my_size();s2.my_size();    //sizes3.my_size();s1.at(1)='o';      //at()函数s1.show();myString s4=s1+s2;   //加法运算符重载s4.show();myString s5("world");   //有参构造s4+=s5;      //+=运算符重载s4.show();s4.my_size();if(s5>s1){cout<<"s5>s1"<<endl;}else{cout<<"s5<=s1"<<endl;}cout<<s4[6]<<endl;return 0;
}

思维导图

http://www.lryc.cn/news/164635.html

相关文章:

  • 2024字节跳动校招面试真题汇总及其解答(二)
  • SpringBoot集成websocket(4)|(使用okhttp3实现websocket)
  • 【MySQL】JDBC编程
  • 数据结构——二叉树线索化遍历(前中后序遍历)
  • GO语言网络编程(并发编程)Channel
  • c++day3
  • 算法通过村第六关-树青铜笔记|中序后序
  • C++动态内存管理+模板
  • SQL 注入漏洞攻击
  • 一篇五分生信临床模型预测文章代码复现——Figure 10.机制及肿瘤免疫浸润(四)
  • Transformer 模型中常见的特殊符号
  • C# halcon SubImage的使用
  • 每天几道Java面试题:异常机制(第三天)
  • Linux 中的 chattr 命令及示例
  • LeetCode 2605. Form Smallest Number From Two Digit Arrays【数组,哈希表,枚举;位运算】1241
  • VoxWeekly|The Sandbox 生态周报|20230904
  • antd setFieldsValue 设置初始值无效AutoComplete 设置默认值失败
  • 01-Redis核心数据结构与高性能原理
  • 预防Dos攻击
  • ant design的文档真的是一坨屎
  • 关于迁移学习的一点理解
  • 【力扣周赛】第 361 场周赛(⭐前缀和+哈希表 树上倍增、LCA⭐)
  • 解决 Android 依赖冲突
  • 前端设计模式基础笔记
  • Python项目开发:Flask基于Python的天气数据可视化平台
  • Dell 服务器常见报错信息汇总
  • 算法通关村-----贪心面试大热门之区间问题
  • OAK相机:自动或手动设置相机参数
  • 百家宴焕新上市,持续深耕100-300元价位段
  • Linux Debian12使用git将本地项目上传到码云(gitee)远程仓库