作业
仿照string类,完成myString 类
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); } //拷贝构造 //析构函数 //拷贝赋值函数 //判空函数 //size函数 //c_str函数 //at函数 char &at(int pos) //加号运算符重载 //加等于运算符重载 //关系运算符重载(>) //中括号运算符重载 };
- #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)
- {
- cout<<"拷贝构造函数"<
- }
- //析构函数
- ~myString()
- {
- delete str;
- cout<<"析构函数"<
- }
- //拷贝赋值函数
- //定义拷贝赋值函数
- 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<<"Stu:: 拷贝赋值函数"<
- return *this; //返回自身引用
- }
- //判空函数
- bool s_empty()
- {
- return !strcmp("",str);
- }
- //size函数
- int s_size()
- {
- return strlen(this->str);
- }
- //c_str函数
- char *s_c_str()
- {
- return str;
- }
- //at函数
- char &at(int pos)
- {
- return str[pos];
- }
- //加号运算符重载
- const myString operator+(const myString &R)const
- {
- myString c;
- c.str=strcat(this->str,R.str);
- c.size=this->size+R.size;
- return c;
- }
- //加等于运算符重载
- myString & operator+=(const myString &R)
- {
- this->str=strcat(this->str,R.str);
- this->size+=R.size;
- return *this;//返回自身的引用
- }
- //关系运算符重载(>)
- bool operator>(const myString &R)const
- {
- return strcmp(this->str,R.str);
- }
- //中括号运算符重载
- char &operator[](int index)
- {
- return str[index];
-
- }
-
- //定义展示
- void show()
- {
-
- cout<<"字符串:"<
- cout<<"实际长度:"<
- }
- };
- int main()
- {
- myString c1("hihihi");
- c1.show();
- myString c2("wwww");
- c2.show();
- myString c3=c1+c2;
- c3.show();
- if(c1>c2)
- {
- cout<<"yes"<
- }
- else
- {
- cout<<"no"<
- }
- c3[0]='A';
- c3.show();
- c3+=c2;
- c3.show();
- cout<<"size="<
s_size()< -
- return 0;
- return 0;
- }

思维导图

-
相关阅读:
详解token已过期含义及解决方 token过期是否需要重新登录
微服务是个坏主意吗?
Flask 用户登录,表单提交
LQ0191 切面条【填空题】
Informer论文思维导图
摩尔信使MThings的设备高级参数
【无标题】This project has been opened by another efinity instance
刷题数据结构实现类
日期格式化 YYYY-MM-DD 出现时间偏移量
深度学习——SAM(Segment-Anything)代码详解
-
原文地址:https://blog.csdn.net/HYL1234511/article/details/132815994