用C++封装一个String
2016-04-16 11:17
441 查看
习惯了C#跟Java以后,使用C++是各种不方便,主要是封装太少,其次C++中的对象思想其实用得并不广泛,而是强调指针,正在努力习惯中。
跟着课程封装了string
mystring头文件
总结起来,这个跟java的私有化结构函数思想一样,但是这个主要是操作指针、数组。学到的东西:new 出来的东西一定要delete,如果下次需要重新使用需要将其置为NULL;
深拷贝的使用方法与情况(有指针存在的时候)。
跟着课程封装了string
#include "mystring.h" #include<string.h> MyString * MyString::ms = NULL; MyString* MyString::MakeMyString(const char *s) { if(ms==NULL) { if(s==NULL) { ms = new MyString(); }else { ms = new MyString(s); } } return ms; } void MyString::set_string(const char *s) { if(this->s==NULL) { int str_len =strlen(s); this->s = new char[str_len+1]; strcpy(this->s,s); this->s[str_len] = 0; } else { int str_len = strlen(s); delete []this->s; this->s = new char[str_len+1]; strcpy(this->s,s); this->s[str_len] = 0; } } char * MyString::getString() const { return s; } void MyString::releaseString() { if(ms!=NULL) { delete ms; ms = NULL;//以供下次再次使用 // return ; }else { // return ; } } MyString::MyString() : s(NULL) { } MyString::MyString(const char *s) { int len = strlen(s); this->s = new char[len+1]; strcpy(this->s,s); this->s[len] = 0; } MyString::~MyString() { delete []s; } MyString::MyString(const MyString &it) { this->s = new char [strlen(it.s)+1]; strcpy(this->s,it.s); this->s = 0; }
mystring头文件
#ifndef MYSTRING_H #define MYSTRING_H class MyString { private: static MyString *ms; char *s; public: static MyString* MakeMyString(const char *s); void set_string(const char *s); char* getString()const; void releaseString(); protected: MyString(); MyString(const char *s); ~MyString(); MyString(const MyString &it); }; #endif // MYSTRING_H
总结起来,这个跟java的私有化结构函数思想一样,但是这个主要是操作指针、数组。学到的东西:new 出来的东西一定要delete,如果下次需要重新使用需要将其置为NULL;
深拷贝的使用方法与情况(有指针存在的时候)。
相关文章推荐
- SDM(Supervised Descent Method)用于人脸对齐的C++实现方法
- C++学习笔记之二 C++基础学习2
- c语言:猴子吃桃问题
- vc++/C++操作mysql数据库一些注意事项
- c++ 初学者,求助,课后习题。
- c++ 开发常用开源库
- Windows文件操作【C/C++】
- c++ 宏的使用
- C++数组和指针的区别详解
- 经常使用哈希函数的比較及其C语言实现
- c++ 大整数类
- c++多重继承的内存分布
- C++下数组随机shuffle的方法
- C++学习 之感
- C++中如何避免资源泄漏
- C++第三次作业
- vc++怎么可以直接刷掉MBR?搞笑的吧
- vc++怎么可以直接刷掉MBR?搞笑的吧
- vc++怎么可以直接刷掉MBR?搞笑的吧
- vc++怎么可以直接刷掉MBR?搞笑的吧