c++;jstring类 写时拷贝 简单实现
2015-12-03 13:24
447 查看
#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; }
相关文章推荐
- The C++ Standard Library: shared_ptr and unique_ptr
- C、c++ .h 头文件的作用
- 如何让一个类不能被继承
- 【C语言提高20】字符串反转(两头堵的变形)
- C++中placement new详解
- 基于双向链表的增删改查和排序(C++实现)
- C语言命名空间
- C++下遍历文件夹内文件
- C++中创建文件夹
- UE4 在C++ 动态生成几何、BSP体、Brush ---- Mesh_Generation
- C++之动态链接库和静态链接库归纳…
- c++ list, vector, map, set 区别与用法比较
- KMP算法--c语言实现
- C++ 对文件夹的操作
- c++友元【转载】
- 设计模式C++实现:组合模式
- C++ Error:C2011: 'struct' type redefinition
- 学习c语言的一些简单经验!
- C++ STL学习之queue
- C语言变量名和地址的关系探讨