#include<iostream> #include<assert.h> #include<malloc.h> #define CAPACITY 3 using namespace std; class String { public: String(char *str="") :_str((char*)malloc(strlen(str)+1)), _size(strlen(str)) { strcpy(_str, str); _capacity = _size+1; cout << "构造函数" << endl; } String(String const&objstr) :_str(NULL), _size(objstr._size), _capacity(objstr._capacity) { String tmp(objstr._str); swap(_str, tmp._str); } ~String() { cout << "析构函数" << endl; if (_str) { free(_str); } } size_t newcapacity(size_t size) { if (size > _capacity) { _str = (char*)realloc(_str, (size + CAPACITY)); } return size + CAPACITY; } void display() { cout << _str << endl; } void Pushback(char str) { int size = _capacity+1; _capacity = newcapacity(size); _str[_size] = str; _str[_size + 1] = ‘\0‘; _size = _size + 1; } int Find(char x) { if (_str == NULL) { return -1; } int i = 0; for (; i <= (int)_size; i++) { if (_str[i] == x) { return i; } } return -1; } void insert(char x, size_t pos) { int size = _size + 1; _capacity = newcapacity(size); int i = _size; for (; i >(int)pos; i--) { _str[i+1] = _str[i]; } _str[pos+1] = x; _size = _size + 1; } String &operator =(String const &str) { if (str._str == NULL) { _str = NULL; _size = str._size; return *this; } _capacity = newcapacity(str._capacity); char *str1 = str._str; strcpy(_str, str1); _size = str._size; return *this; } int &operator>(String const &str) { int ret = strcmp(_str, str._str); return ret; } private: char * _str; size_t _size; size_t _capacity; }; void Test1() { String str1("abcdef"); String str2(str1); int ret=str2.Find(‘d‘); str2.insert(‘x‘, ret); str2.Pushback(‘a‘); cout << ret << endl; str2.display(); } void Test2() { String s1("abcdef"); String s2("efghlmn"); s1 = s2; s1.display(); } int main() { //Test1(); Test2(); return 0; }
时间: 2024-10-05 05:32:24