#include<iostream>//頭文件 #pragma once using namespace std; class String { private: char* _string; int* _strCount; size_t _size; size_t _capacity; public: String(const char* str = "\0"); String(const String& str); ~String(); char& operator[](int index); char* GetChar(); void operator =(String & str); }; #include<iostream>//函數文件 #include"string.h" using namespace std; String::String(const char* str) { _string = new char[strlen(str) + 5]; _strCount=(int*)_string ; _string = _string + 4; strcpy(_string, str); *_strCount = 1; _size = (strlen(str)); _capacity = _size + 1; } String::String(const String& str) { _string = str._string; ++*(str._strCount); _strCount = str._strCount; _size = str._size; _capacity = str._capacity; } String::~String() { if (*_strCount > 1) --(*_strCount); else delete[] _strCount; } char& String:: operator[](int index) { if (*_strCount != 1) { --*_strCount; char* tmp = new char[strlen(_string) + 5]; strcpy(tmp + 4, _string); _strCount = (int*)tmp; *_strCount = 1; _size = strlen(_string); _capacity = _size + 1; _string = tmp + 4; } return _string[index]; } char* String::GetChar() { return _string; } void String::operator =(String & str) { _string = str._string; ++*(str._strCount); _strCount = str._strCount; _size = str._size; _capacity = str._capacity; } #include<iostream>//主函數 測試文件 #include"string.h" using namespace std; void test1() { String s1("woshishuaige"); String s2(s1); String s3; cout << s1.GetChar() << endl; cout << s2.GetChar() << endl; cout << s3.GetChar() << endl; s2[0] = 1; cout << s2.GetChar() << endl; } int main() { test1(); return 0; }