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)
{
size = strlen(s);
str = new char[size+1];
strcpy(str, s);
}
//拷贝构造函数
myString(const myString &other):str(new char(*(other.str))),size(other.size)
{
strcpy(this->str,other.str); //拷贝字符串
this->size = other.size; //拷贝字符串长度
cout<<"myString::拷贝构造函数 str = "<}
//析构函数
~myString()
{
delete str;
cout<<"myString::析构函数 this = "< }//拷贝赋值函数myString & operator=(const myString &other){if(this != &other){strcpy(this->str, other.str);this->size = other.size;}cout<<"myString::拷贝赋值函数 str = "<return *this; }//判空函数bool empty(){return 0==size;}//size函数int myString_size(){return strlen(str);}//c_str函数const char *c_str(){return this->str;}//at函数char &at(int pos){return str[pos-1];}//加号运算符重载const myString operator+(const myString &str)const{myString temp;temp.size = this->size+str.size;temp.str = strcat(temp.str, this->str);temp.str = strcat(temp.str, str.str);return temp;}//加等于运算符重载const myString operator+=(const myString &str){strcat(this->str, str.str);this->size = strlen(this->str);return *this;}//关系运算符重载bool operator >(const myString &s)const{if(this->size < s.size){return false;}else{for(int i=0;isize;i++){ if(*(this->str+i)<*(s.str+i)){return false;}}}return true;}//中括号运算符重载char & operator[](const int pos)const{if(pos>=size || pos<0){cout<<"访问越界"< }return *(str+pos);}};int main(){myString s1("hello world");myString s2(s1);myString s3;s3 = s2;cout << "字符串长度为:" < cout<<"at(1) = "< cout<<"c_str: "< return 0;}2、思维导图