作业
仿照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 <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,""); //赋值为空串}//有参构造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<<"拷贝构造函数"<<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.str);}cout<<"Stu:: 拷贝赋值函数"<<endl;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<<"字符串:"<<str<<endl;cout<<"实际长度:"<<size<<endl;}
};
int main()
{myString c1("hihihi");c1.show();myString c2("wwww");c2.show();myString c3=c1+c2;c3.show();if(c1>c2){cout<<"yes"<<endl;}else{cout<<"no"<<endl;}c3[0]='A';c3.show();c3+=c2;c3.show();cout<<"size="<<c3.s_size()<<endl;return 0;return 0;
}
思维导图