1、仿照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)
- {
- 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 str_empty()
- {
- return !strcmp("",str);
- }
-
- //size函数
- int str_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("hello ");
- c1.show();
- myString c2("world");
- c2.show();
- myString c3=c1+c2;
- c3.show();
- if(c1>c2)
- {
- cout<<"yes"<
- }
- else
- {
-
-
相关阅读:
.NET的键盘Hook管理类,用于禁用键盘输入和切换
Rust 登上了开源头条「GitHub 热点速览」
短视频账号矩阵系统saas管理私信回复管理系统
js 内存泄露,几种常涉及到的内存泄露
优化软件测试成本的 7 个步骤
【Java面试】Spring中 BeanFactory和FactoryBean的区别
vue的diff算法
MQTT 基础--MQTT 协议简介 :第 1 部分
实践 缓存
办公软件WPS与Office的区别
-
原文地址:https://blog.csdn.net/A18801772899/article/details/132817697