#include<iostream>
#include<cstring>
using namespace std;
class myString {
public:
myString(const char* str = "") {
strSize = strlen(str) + 1;
this->str = new char[strSize];
strcpy_s(this->str, strSize, str);
}
myString(const myString& object) {
strSize = object.strSize;
this->str = new char[strSize];
strcpy_s(this->str, strSize, object.str);
}
char* c_str() {
return str;
}
char* data() {
return str;
}
~myString(){
delete[] str;
str = nullptr;
}
myString append(const myString& object) {
myString temp;
temp.strSize = myString::strSize + object.strSize - 1;
temp.str = new char[temp.strSize];
memset(temp.str, 0, temp.strSize);
strcat_s (temp.str, temp.strSize, myString::str);
strcat_s (temp.str, temp.strSize, object.str);
return temp;
}
int compare(const myString& object) {
return strcmp(myString::str, object.str);
}
protected:
char* str;
int strSize;
};
//1.实现string中创建方式
int main() {
myString str1;
myString str2("ILoveyou");
myString str3(str1);
myString str4 = str2;
//2.通过实现data和c_str函数 打印字符串
cout << str2.c_str() << endl; //打印ILoveyou
cout << str2.data() << endl; //打印ILoveyou
//3.实现append 实现字符串的链接
myString strOne = "one";
myString strTwo = "two";
myString strThree = strOne.append(strTwo);
cout << strThree.data() << endl; //onetwo
//4.实现字符串比较
cout << strOne.compare(strOne) << endl; //0
//5.手写析构函数释放内存
return 0;
}
|