自己写一个string类
如:
代码:
#include <iostream>
#include <cstring>
using namespace std;
class Mystring{
private:
int len;
char* str;
public:
//无参构造函数
Mystring(){
len = 0;
str = nullptr;
}
//有参构造函数
Mystring(const char* s){
len = strlen(s);
str = new char[len];
strcpy(str,s);
}
//拷贝构造函数
Mystring(Mystring &s):len(s.len),str(new char[s.len])
{
// len = s.len;
// //str = s.str;
// new char[len];
strcpy(str,s.str);
}
//拷贝赋值函数
Mystring& operator=(const Mystring &s){
if(&s == this)
return *this;
len = s.len;
if(nullptr == str){
str = new char[s.len];
}
strcpy(str,s.str);
return *this;
}
//析构函数
~Mystring(){
cout<<&str<<"析构函数\n";
if(nullptr != str)
delete []str;
str = nullptr;
}
//c_str()
char* myc_str(){
return this->str;
}
//length()
int mylength(){
return this->len;
}
//empty()
bool myempty(){
cout<<"判空\n";
if(len == 0){
return 1;
}
return 0;
}
//at()
char& myat(int x){
if(x>=len || x<0)
throw "数组下标越界!\n";
return str[x];
}
};
int main(int argc, const char *argv[])
{
Mystring str0;
cout<<str0.myempty()<<endl;
Mystring str1("12345");
str0 = str1;
cout<<"str1="<<str1.myc_str()<<"\nlen="<<str1.mylength()<<endl;
cout<<"str0="<<str0.myc_str()<<"\nlen="<<str0.mylength()<<endl;
str0.myat(3) = 'h';
cout<<"str0="<<str0.myc_str()<<"\nlen="<<str0.mylength()<<endl;
try{
str0.myat(10) = 'j';
}catch(const char* err){
cerr<<err;
//cout<<str0.myc_str()<<endl;
}
Mystring str2(str0);
cout<<"str2="<<str2.myc_str()<<"\nlen="<<str2.mylength()<<endl;
return 0;
}