#include <iostream>
#include <cstring>
using namespace std;
class mystring{
public:
mystring(const char *str = nullptr){
if(str==nullptr){
data = new char[1];
data[0] = '\0';
len = 0;
}else{
len = strlen(str);
data = new char[len + 1];
strcpy(data, str);
}
}
mystring(const mystring& str){
len = str.len;
data = new char[len+1];
strcpy(data, str.data);
}
mystring& operator=(const mystring &str){
if(this == &str) return *this;
delete[] data;
len = strlen(str.data);
data = new char[len + 1];
strcpy(data, str.data);
return *this;
}
mystring& operator+=(const mystring& str){
int len1 = len;
int len2 = str.len;
char *p = str.data;
char* tmp = new char[len1 + len2 + 1];
char* head = tmp;
while(*data){
*tmp++ = *data++;
}
while(*p){
*tmp++ = *p++;
}
*tmp = '\0';
data = head;
len = len1 + len2;
return *this;
}
~mystring(){
delete[] data;
}
char* c_str(){
return data;
}
int size(){
return len;
}
private:
char *data;
int len;
};
int main(){
mystring ms("abcd");
mystring tz = ms;
cout<<tz.c_str()<<tz.size()<<endl;
cout<<ms.c_str()<<ms.size()<<endl;
mystring ta(ms);
ta += tz;
cout<<ta.c_str()<<ta.size()<<endl;
}
c++实现string类
最新推荐文章于 2024-03-07 20:54:21 发布