代码:
#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)+1;str = new char[size];strcpy(str, s);}//拷贝构造myString(char *s,int i):str(new char(*s)),size(i){strcpy(this->str,s);this->size = i;cout<<"拷贝构造函数"<<endl;}//析构函数~myString(){delete str;}//拷贝赋值函数myString &operator = (const myString &other){if(&other != this){this->str = new char[size];memset(str,0,size);strcpy(str,other.str);}return *this;}//判空函数bool empty(){if(strlen(str) == 0)return false;elsereturn true;}//size函数int mysize(){return size;}//c_str函数const char* c_str(){return str;}//at函数char &at(int pos){if(pos>=size || pos<0){cout<<"访问越界"<<endl;}return str[pos];}//加号运算符重载const myString operator+(const myString &s)const{myString m;strcpy(m.str,this->str);strcat(m.str,s.str);m.size = strlen(m.str);return m;}//加等于运算符重载const myString operator+=(const myString &s){strcat(this->str,s.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;i<this->size;i++){if(*(this->str+i)<*(s.str+i)){return false;}}}return true;}//中括号运算符重载char & operator[](const int pos)const{if(pos>=size || pos<0){cout<<"访问越界"<<endl;}return *(str+pos);}
};int main(){//展示字符串myString s1("ssssyyyy");myString s2("wwwwhhhh");cout<<s1.c_str()<<" "<<s2.c_str()<<endl;//重载加法运算符myString s3;cout<<s3.mysize()<<endl;s3=s1+s2;cout<<s3.c_str()<<endl;//at运算cout<<s3.at(3)<<endl;//加等于s3+=s1;cout<<s3.c_str()<<endl;cout<<s3.mysize()<<endl;//关系运算if(s3>s1){cout<<"s3>s1"<<endl;}elsecout<<"s3<s1"<<endl;//中括号cout<<s2[3]<<" "<<s2[6]<< " "<<s2[8]<<endl;return 0;
}