模拟实现C++ string类(构造、析构、拷贝、赋值运算符重载)
2016-08-04 09:00
549 查看
在面试过程中,如果要让写一个string类的模拟,那么,面试官多半是想考你关于深浅拷贝的某些知识。
对于string类的实现来说,比较重要的几个成员函数,也就是构造函数、析构函数、拷贝构造函数、赋值运算符重载等等,再次,我只先实现这几个。其中拷贝构造和赋值运算符的重载有其他方法,我将在后边附上写出来。
废话不多,直接上程序:
对于拷贝构造函数和赋值运算符的重载还有其他方法来实现。
拷贝构造:
(2)再利用swap函数将strTemp的_pstr与要构造的对象(this)的_pstr进行交换,由于之前已经给(this)的_pstr赋空,所以交换之后,strTemp的_pstr为NULL。
(3)拷贝构造函数调用完之后会析构strTemp对象。
赋值运算符重载:
上边两种赋值运算符重载的方式其实大同小异,都是利用了建立新对象和swap交换函数。
(1)重载一中,在传参的时候,是复制了一份临时变量(对象)s,利用s的_pstr和被赋值对象(this)的_pstr进行交换,使得被赋值对象(this)的_pstr指向s._pstr,而s.pstr指向原本this._pstr的指向。
(2)重载二中,参数是利用引用的,但在函数内部,还是创建了对象strTemp,再利用交换函数,得到正确的指向。
对于string类的实现来说,比较重要的几个成员函数,也就是构造函数、析构函数、拷贝构造函数、赋值运算符重载等等,再次,我只先实现这几个。其中拷贝构造和赋值运算符的重载有其他方法,我将在后边附上写出来。
废话不多,直接上程序:
<pre name="code" class="cpp">class String { public: char* _pstr; public: String(char* pstr="")//构造函数 { if (pstr == NULL) { _pstr = new char[1]; *_pstr = '\0'; } else { _pstr = new char[strlen(pstr) + 1]; strcpy(_pstr,pstr); } } String(const String&s)//拷贝构造函数 { _pstr = new char[strlen(s._pstr) + 1]; strcpy(_pstr, s._pstr); } ~String()//析构函数 { if (_pstr) { delete[] _pstr; } } String& operator = (const String& s)//赋值运算符重载 { if (this != &s) { char *pstr = new char[strlen(s._pstr) + 1]; strcpy(pstr, s._pstr); delete[] _pstr; _pstr = pstr; } return *this; }
<pre name="code" class="cpp">int main() { String s1("hallo world"); cout << s1._pstr << endl; String s2(s1); cout << s2._pstr << endl; String s3 ; s3 = s2; cout << s3._pstr << endl; return 0; }
对于拷贝构造函数和赋值运算符的重载还有其他方法来实现。
拷贝构造:
String(const String &s)//拷贝构造 :_pstr(NULL) { String strTemp(s._pstr); std::swap(_pstr, strTemp._pstr); cout << "this is copy " << this << endl; }(1) 以上拷贝构造函数先在函数内部用构造函数构造了一个局部对象strTemp,其中strTemp的_pstr的指向用参数S的_pstr构造。
(2)再利用swap函数将strTemp的_pstr与要构造的对象(this)的_pstr进行交换,由于之前已经给(this)的_pstr赋空,所以交换之后,strTemp的_pstr为NULL。
(3)拷贝构造函数调用完之后会析构strTemp对象。
赋值运算符重载:
String& operator =( String s)//赋值运算符重载一 { std::swap(_pstr, s._pstr); return *this; } String& operator =(const String &s)//赋值运算符重载二 { if (this != &s) { String strTemp(s); std::swap(_pstr, strTemp._pstr); } return *this; }
上边两种赋值运算符重载的方式其实大同小异,都是利用了建立新对象和swap交换函数。
(1)重载一中,在传参的时候,是复制了一份临时变量(对象)s,利用s的_pstr和被赋值对象(this)的_pstr进行交换,使得被赋值对象(this)的_pstr指向s._pstr,而s.pstr指向原本this._pstr的指向。
(2)重载二中,参数是利用引用的,但在函数内部,还是创建了对象strTemp,再利用交换函数,得到正确的指向。
相关文章推荐
- C数组名与指针,sizeof与strlen,free与delete区别,野指针,编译过程简介
- 8.3总结
- c++之STL(13) STL 算法 - 查找算法(1)
- C++系列——const,引用,指针用法小结
- c/c++第九天
- c++
- 复数类的完整实现(C++版)
- C++编译期多态与运行期多态
- c++运算符重载总结
- C++拷贝构造函数(深拷贝,浅拷贝)
- make j* make j4 make j8 区别
- 谁说C语言很简单?
- C语言谜题
- C++中的“流”和fstream类的一点总结
- C++中关于复杂的多维数组声明的总结
- c++之封装——string类型的实现
- 编程能力提高-----C/C++指针详解
- C++中getline与C中scanf、gets小结
- c语言fwrite 换行
- Regex C++ : 正则表达式(2).