编写类 String 的构造函数、析构函数和赋值函数

#include <iostream>
#include<string>
using namespace std;
class String
{
public:

    friend ostream &operator<<(ostream& os, String& s);

    //这个版本需要考虑用一个赋值String str1(str2);
    //当str2为空字符串,调用拷贝构造函数时strlen不能求空字符串的值,导致
    //程序崩溃问题
    //String()  //默认构造函数     
    //  :_str(NULL)
    //{
    //  cout << "String()" << endl;
    //}


    //String() 
    //  :_str (new char[1])
    //{
    //  cout << "String()" << endl;
    //  *_str = '/0';
        *_str = "/0";
    //}

    //String(const char * s)   
    //  :_str (new char[strlen(s)+1])
    //{
    //  cout << "String(const char *s)" << endl;
    //  strcpy(_str, s);
    //}


    //将默认构造和构造函数合并
    String(const char * s="")   
        :_str (new char[strlen(s)+1])
    {
        cout << "String(const char *s)" << endl;
        strcpy(_str, s);
    }



    String(const String &s)   //拷贝构造传参必须是引用  
        :_str(new char[strlen(s._str)+1] )  
        //并未考虑空指针传给strlen的问题
    {
        cout << "String(const String &s)" << endl;
            strcpy(_str,s._str);
    }


    //String & operator=(const String &s)  
    //{
    //  cout << "String & operator=(const String &s)" << endl;
    //  if (s._str != _str)  
     //如果不考虑自赋值问题,可能导致自身内容被销毁
    //  {
    //      delete[]_str;
    //      _str = new char[strlen(s._str) + 1];
    //      strcpy(_str, s._str);
    //  }
    //  return *this;
    //}

    //现代写法
    String & operator=( String s)  
    //如果是引用会导致原来申请的堆空间未释放
    {
        cout << "String & operator=(const String &s)" << endl;
        std::swap(_str, s._str); 
         //s是实参的一份临时拷贝,所以出了这个函数作用域,会自行销毁
        return *this;
    }

    ~String()
    {
        cout << "~String()" << endl;
        if (_str != NULL)
        {
            delete[]_str;
        }
    }

private:
    char* _str;
};

ostream &operator<<(ostream& os, String& s)
{
    os << s._str;
    return os;
}

int main()
{
    //string str = "abcdef";
    //string str1 = str;
    String str1("abcdef");
    //String str2(str1);
    String str3 ;
    str3 = str1;
    cout << str1 << endl;
    cout << str3 << endl;
    //cout << str2 << endl;
    //cout << str1 << endl;
    return 0;
}

总结:

   在实现时要考虑内存泄漏问题,在实现赋值时非现代版本考虑自赋值问题所带来的后果,以及实现默认构造函数将指针置空,会带来什么后果,以及什么时候该用引用,什么时候不该用。以及要注意的是strlen不能传一个空指针让它去求字符串的长度等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值