1> 仿照string类,实现myString类
#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) { strcpy(this->str,other.str); } //析构函数 ~myString() { delete []str; str = nullptr; } //拷贝赋值函数 myString & operator=(const myString &other) { this->str = new char(*(other.str)); this->size = other.size; strcpy(this->str,other.str); return *this; } //判空函数 bool empty1() { return *(str)=0?1:0; } //size函数 int size1() { return size; } //c_str函数 char* &c_str() { return str; } //at函数 char &at(int pos) { return *(str+pos); } //加号运算符重载 myString &operator + (const myString &R) { this->str = strncat(this->str,R.str,R.size); return *this; } //加等于运算符重载 myString &operator += (const myString &R) { char *temp = this->str; delete [] str; this->size = R.size + this->size; this->str = new char[this->size + 1]; strcpy(this->str, temp); strcpy(this->str, R.str); return *this; } //关系运算符重载(>) bool operator >(const myString &R) { if(strcmp(this->str,R.str)>0) return true; else if(strcmp(this->str,R.str)<0) return false; } }; int main() { myString str1; myString str2("ni hao"); cout<<str2.c_str()<<endl;//有参构造 str1= str2; cout<<str1.c_str()<<endl;//拷贝构造 myString str3(str1); cout<<str3.c_str()<<endl; //拷贝赋值 myString str4("zhangsan"); myString str5("lisi"); myString str6=str4+str5; cout<<str6.c_str()<<endl; //加运算符 myString str7=str4+str5; cout<<str7.c_str()<<endl; //加等于运算符 return 0; }