字符串类的实现:构造函数、析构函数、复制构造函数和赋值操作符

强调一下几个重点:

(1)new 操作符申请内存失败,是抛出异常,并不是返回NULL,若想申请失败返回NULL,需要加 (std::nothrow);

(2)使用std::nothrow 需要加头文件 #include<new>

(3)使用assert

(4)构造函数有参数时最好加默认参数,这样就有默认构造函数了,且不要忘了定义为const

(5)赋值操作符函数体if语句中的条件必须是 this != &other,为什么if(*this != other)不行????

         刚想了下原因是:定义的类型没有!=操作符啊,怎么可以比较呢,只能比较指针了。。。

#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<iostream>
#include<new>
using namespace std;

class String
{
    private:
        char *m_data;

    public:
        String(const char *str = NULL);
        ~String();
        char * get_m_data() {return m_data;}
        String(const String&);
        String& operator= (const String &);
};

String::String(const char *str)
{
    if(str == NULL)
    {
        m_data = new (std::nothrow) char[1];
        assert(m_data != NULL);
        *m_data = '\0';
    }else
    {
        m_data = new (std::nothrow) char[strlen(str) + 1];
        assert(m_data != NULL);
        strcpy(m_data, str);
    }
}

String::~String()
{
    if(m_data != NULL)
    {
        delete []m_data;
        m_data = NULL;
    }
}

String::String(const String &other)
{
    m_data = new (std::nothrow) char[strlen(other.m_data) + 1];
    assert(m_data != NULL);
    strcpy(m_data, other.m_data);
}

String& String::operator= (const String &other)
{
    if(this != &other)
    {
        String tmp(other);
        char *str = tmp.m_data;
        tmp.m_data = m_data;
        m_data = str;
    }

    return *this;
}

int main()
{
    String s1("a big brother is watching you!!!");
    String s2(s1);
    //printf("haha\n");
    String s3;
    s3 = s1;

    printf("%s\n", s1.get_m_data());
    printf("%s\n", s2.get_m_data());
    printf("%s\n", s3.get_m_data());

    return 0;
}


  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值