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

原型如下:

class String

{
public:
    String(const char *str=NULL);// 普通构造函数 
    String (const String &other);// 拷贝构造函数 
    ~String(void);//析构函数 
    String & operator = (const String &other);// 赋值函数 
private:
    char *m_data; // 用于保存字符串 

};

//编写类String的构造函数、析构函数和赋值函数,已知类String的原型为:
class String
{
public:
    String(const char *str=NULL);// 普通构造函数
    String (const String &other);// 拷贝构造函数
    ~String(void);//析构函数
    String & operator = (const String &other);// 赋值函数
private:
    char *m_data; // 用于保存字符串
};
//1、构造函数
/*


   1、构造函数在构造对象时使用;
   2、传入参数的判断;
   3、对象的初始化问题。
*/
String::String(const char *str)
{
    cout << "构造" <<endl;
    if(str == NULL)
    {
        m_data = new char[1];
        *m_data = '\0';
    }
    else
    {
        int len =strlen(str);
        m_data = new char[len+1];
        strcpy(m_data,str);
    }
}
//2、拷贝构造函数
/*
   1、拷贝构造函数必须在构造对象时使用,即定义对象时;
   2、对象初始化问题。
*/
String::String(const String &other)
{
    cout << "拷贝构造" <<endl;
    int len = strlen(other.m_data);
    m_data=new char[len+1];
    strcpy(m_data,other.m_data);
}
//3、赋值函数
/*
   1、赋值函数使用时,对象肯定已经建立;
   2、赋值前,判断是否是自我赋值;
   3、赋值前,内存空间的准备:
       由于赋值前,对象已占有一定大小内存,但是赋值对象所占内存大小与
       对象已占的内存大小不一定一致;
       先释放对象已占的内存,然后分配心内存。
   4、正常赋值
*/


String & String::operator=(const String &other )
{
    cout << "赋值" <<endl;
    if(&other==this)
        return *this;
    delete [] m_data ;
    int len =strlen(other.m_data);
    m_data = new char[len+1];
    strcpy(m_data,other.m_data);
    return *this;
}


//4、析构函数
/*
   资源的释放
*/
String ::~String(void)
{
    cout << "析构" <<endl;
    delete [] m_data;
}
int main()
{
    String a("hello");
    String b("world");
    String c(a);
    c=b;
    return 0;
}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值