C++面试题模拟实现String

来源:互联网 发布:网络科学导论 课程 编辑:程序博客网 时间:2024/05/29 15:33

C++ 的一个常见面试题是让你实现一个 String 类,通常面试官只会给十五分钟左右,不可能要求具备 std::string 的功能,但至少要求能正确管理资源不存在内存泄漏。具体来说:
需要编写构造函数;拷贝构造函数;析构函数;运算符重载=;
【一】传统写法:该开辟空间,开辟空间;该释放空间,释放空间;
可读性高,符合人的思维;

#define _CRT_SECURE_NO_WARNINGS 1#include<iostream>#include<assert.h>using namespace std;class String{public:    friend ostream& operator<<(ostream& os, const String& s);    String( const char* str = "")        :_str(new char[strlen(str)+1])    {        strcpy(_str, str);    }    String(const String& s)        :_str(new char[strlen(s._str)+1])    {        strcpy(_str, s._str);    }    String& operator=(const String&s)    {        if (_str != s._str)        {            //  delete[] _str; //先释放_str,再申请空间如果申请不到,            //_str = new char[strlen(s._str)+1]; //还毁坏了原有数据,得不偿失            //strcpy(_str, s._str);            char* tmp = new char[strlen(s._str) + 1];            strcpy(tmp, s._str);            delete[]_str;            _str = tmp;        }        return *this;    }    ~String()    {        if (_str != NULL)        {            delete[]_str;            _str = NULL;        }    }private:    char* _str;};ostream& operator<<(ostream& os, const String& s){    os << s._str;    return os;}int main(){    String s1("abcdefg");    String s2(s1);    String s3 ;    s3 = s2;    cout << s2 << endl;    cout << s3 << endl;    return 0;}

【二】现代写法:建立一个中间对象tmp,出了这个作用域tmp会自动调用析构函数,代码简洁;

#define _CRT_SECURE_NO_WARNINGS 1#include<iostream>#include<assert.h>using namespace std;class String{public:    friend ostream& operator<<(ostream& os, const String& s);    String( const char* str = "")        :_str(new char[strlen(str)+1])    {        strcpy(_str, str);    }    String(const String& s)        :_str(NULL)    {        String tmp(s._str);        swap(_str, tmp._str);    }    /*String& operator=(const String& s)    {        if (this != &s)  //这种在函数里边调用        {                //拷贝构造函数产生临时变量            String tmp(s);//不如直接采用值传递方便            swap(_str, tmp._str);        }        return *this;    }*/    String& operator=(String s)    {    swap(_str, s._str);    return *this;    }    ~String()    {        if (_str != NULL)        {            delete[]_str;            _str = NULL;        }    }private:    char* _str;};ostream& operator<<(ostream& os, const String& s){    os << s._str;    return os;}int main(){    String s1("abcdefg");    String s2(s1);    String s3 ;    s3 = s2;    cout << s1 << endl;    cout << s2 << endl;    cout << s3 << endl;    return 0;}

如下图所示对现代写法的tmp进行描述:

这里写图片描述

0 0
原创粉丝点击