您的位置:首页 > 编程语言 > C语言/C++

模拟实现C++ string类(构造、析构、拷贝、赋值运算符重载)

2016-08-04 09:00 549 查看
        在面试过程中,如果要让写一个string类的模拟,那么,面试官多半是想考你关于深浅拷贝的某些知识。

        对于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,再利用交换函数,得到正确的指向。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: