自定义String类(C++)----------测试(一)

题目:请写出下面这个类的方法代码

class String
{
public:
    String(char *pstr);
    ~String();
    String(const String &src);
    void operator=(const String &src);
private:
    char *_pstr;
};

这是一个C++题目,要求写出构造函数、析构函数、拷贝构造函数和赋值函数。为什么会有拷贝构造函数和赋值函数?主要是因为字符串在堆上开辟了空间,当一个对象赋值给另一个对象时会发生浅拷贝,为了避免这种情况的发生,需要自定义拷贝构造函数和赋值函数。

实现

构造函数
String::String(const char *str)
{
    if (str!=NULL)
    {
        m_data = new char[strlen(str) + 1];
        strcpy(m_data,str);
        cout << this;
        cout << "调用one构造函数" << endl;
    }
    else
    {
        m_data = new char[1];
        *m_data = '\0';
        cout << this;
        cout << "调用two构造函数" << endl;
    }
}

带了默认参数,则我们需要对参数指针判空,,然后分别处理。

析构函数
String::~String()
{
    delete[]m_data;
    m_data = NULL;
    cout << this;
    cout << "调用析构函数函数" << endl;
}

析构函数主要是在对象内存释放之前,归还系统所借用的外部资源。在字符串对象的生成过程中,占用了堆上的内存,故需要对该部分内存进行释放。

拷贝构造函数
String::String(const String &other)
{
    m_data = new char[strlen(other.m_data) + 1];
    strcpy(m_data,other.m_data);
    cout << this;
    cout << "调用拷贝构造函数" << endl;
}

为了避免两个对象指向同一个堆内存,则最直接的方法就是对另一个对象重新开辟内存,再赋值。

赋值函数
void String::operator=(const String &other)
{
    if (this == &other)
    {
        return;
    }
    delete[]m_data;

    m_data = new char[strlen(other.m_data) + 1];
    strcpy(m_data, other.m_data);
    cout << this;
    cout << "调用赋值函数" << endl;
}

在赋值函数中,需要防止自赋值,并且把当前对象原先所占的资源释放掉。最后再开辟空间,并填充空间。

测试

int main(int argc, _TCHAR* argv[])
{
    char *str = "cnvailfbvibe";
    String s(str);    //调用one构造函数
    String s1(NULL);  //调用two构造函数

    String str2(s);  //调用拷贝构造函数
    String str3;     //调用two构造函数
    str3 = str2;     //调用赋值函数

    return 0;
}

运行结果
这里写图片描述
可以看出,析构函数顺序和构造函数顺序相反。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值