目录
- #include
- #include
-
- using namespace std;
-
- class myString
- {
- private:
- char *str; //记录c风格的字符串
- int size; //记录字符串的实际长度
- public:
- //无参构造
- myString():size(10)
- {
- str = new char[size]; //构造出一个长度为10的字符串
- strcpy(str,""); //赋值为空串
- cout<<"无参构造"<
- }
- //有参构造
- myString(const char *s) //string s("hello world")
- {
- size = strlen(s);
- str = new char[size+1];
- strcpy(str, s);
- cout<<"有参构造"<
- }
-
- //拷贝构造
- myString(const myString &other)
- {
- this->str=new char[other.size+1];
- strcpy(str,other.str);
- this->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.size+1];
- strcpy(str,other.str);
- cout<<"拷贝赋值"<
- }
- return *this;
- }
-
- //判空函数
- bool empty()
- {
- return 0==size;
- }
-
- //size函数
- int my_size()
- {
- cout<<strlen(str)<
- 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<<"数组越界"<
- }
- }
-
- void show()
- {
- cout<
- }
- };
-
- int main()
- {
- char arr[10]="hello";
- myString s1(arr); //有参构造
-
- myString s2=s1; //拷贝构造
-
- myString s3; //无参构造
- s3=s2; //拷贝赋值函数
-
- s1.my_size();
- s2.my_size(); //size
- s3.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"<
- }else
- {
-
-
相关阅读:
10款轻量型的嵌入式GUI库分享
安卓APP源码和设计报告——仿淘宝水果商城
手撕链式二叉树(二)—【C语言】
Java --- SpringMVC的HttpMessageConverter
以数智化驱动为核心,构建研发效能增长动力
R语言:利用biomod2进行生态位建模
实现一个动态规划算法,解决背包问题
vue面试经常会问的那些题
seata案例搭建
NC14700 追债之旅 (拆点+最短路)
-
原文地址:https://blog.csdn.net/weixin_58469613/article/details/132817926