#include < iostream > using namespace std;
class mystring {
public: mystring() : mystr(NULL) {}
// 构造函数
mystring(char * str) {
if (mystr != NULL) {
mystr = NULL;
}
mystr = new char[sizeof(str) + 1];
strcpy(mystr, str);
}
// 拷贝构造
mystring(mystring & myst) {
if (mystr != NULL) {
mystr = NULL;
}
mystr = new char[sizeof(myst.mystr) + 1];
strcpy(mystr, myst.mystr);
}
// 赋值运算符
mystring & operator = (mystring & str) {
if (this != &str) {
if (mystr != NULL) {
mystr = NULL;
}
mystr = new char[sizeof(str.mystr) + 1];
strcpy(mystr, str.mystr);
}
return * this;
}
// 析构函数
~mystring() {
if (mystr != NULL) {
delete[] mystr;
mystr = NULL;
}
}
// 重置函数
char * chongzhi(char * str) {
if (mystr != NULL) {
delete[] mystr;
mystr = NULL;
}
mystr = new char[sizeof(str) + 1];
strcpy(mystr, str);
return mystr;
}
// 清空函数
bool qingkong() {
if (mystr != NULL) {
delete[] mystr;
mystr = NULL;
}
return true;
}
// 返回长度
int changdu() {
if (mystr == NULL) return 0;
return (int) strlen(mystr);
}
// 返回索引
char index(int index) {
if (mystr == NULL) return false;
return mystr[index];
}
bool index2(int index, char ch) {
if (mystr == NULL) return false;
mystr[index] = ch;
return true;
}
// 打印整个字符串
char * dayin() {
if (mystr == NULL) return "你没有赋值";
return mystr;
}
// 查找字符位置
char find(int a) {
return mystr[a];
}
char * dayinzfhuan(int a) {
char * p = &mystr[a];
return p;
}
// 插入字符
bool insert(int a, char * p) {
char * temp;
temp = (char * ) malloc(sizeof(mystr) + sizeof(char));
for (int i = 0; i < a; i++) {
temp[i] = mystr[i];
}
temp[a] = *p;
for (int i = a + 1; i < strlen(mystr); i++) {
temp[i] = mystr[i];
}
delete[] mystr;
mystr = temp;
return true;
}
// 删除字符
bool delet(int a) {
char * temp;
temp = (char * ) malloc(sizeof(mystr) - sizeof(char));
for (int i = 0; i < a; i++) {
temp[i] = mystr[i];
}
for (int i = a + 1; i < strlen(mystr); i++) {
temp[i - 1] = mystr[i];
}
delete[] mystr;
mystr = temp;
return true;
}
private: char * mystr;
};
int main() {
mystring mystr9("allenboy");
mystr9.delet(3);
mystr9.insert(3, "A");
cout << mystr9.dayin() << endl;
//
// mystring* mystr = new mystring("str");
// mystr->changdu();
// mystr->chongzhi("allen");
// mystr->index2(3, 'A');
// cout<<mystr->changdu()<<endl;
// cout<<mystr->index(3)<<endl;
// cout<<mystr->dayin()<<endl;
// mystring mystr2 = *mystr;
// mystring mystr22(*mystr);
// cout<<mystr2.dayin()<<endl;
// mystr2.index2(3, 'B');
// cout<<mystr->dayin()<<endl;
// cout<<mystr2.dayin()<<endl;
// mystring mystr3 =*mystr;
// mystring mystr4("allenboy");
// mystring mystr5;
// mystring mystr6 = mystr4;// 调用复制构造函数
// // 初始化才会调用复制构造函数,其它的都调用赋值运算符.
// mystring mystr7;
// mystring mystr8;
// mystr8=mystr4; // 调用赋值运算符
// cout<<mystr4.dayin()<<endl;
// cout<<mystr5.dayin()<<endl;
// cout<<mystr8.dayin()<<endl;
// cout<<mystr6.dayin()<<endl;
// cout<<mystr6.dayinzfhuan(3)<<endl;
// cout<<mystr6.find(3)<<endl;
return 0;
}
来源: http://www.bubuko.com/infodetail-2482875.html