自定义String类模型

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hhhuang1991/article/details/79830240
//MyString.h
#pragma once
#include <iostream>
class MyString
{
public:
    MyString(const char* str = nullptr);  
    MyString(const MyString& other);   
    MyString& operator=(const MyString& other);  
    ~MyString();  //析构函数
private:
    char* m_data;
};

//MyString.cpp
#include "MyString.h"
MyString::MyString(const char* str = NULL)
{
    if (NULL == str)
    {
        m_data = new char[1];
        m_data[0] = ' ';
        return;
    }
    int len = strlen(str);
    m_data = new char[len + 1];
    strcpy(m_data, str);
}
MyString::~MyString()
{
    delete[] m_data;
}


/** 
* @brief 拷贝构造函数,调用形式:
* MyString str1 = "China";   //调用普通构造函数
* MyString str = str1;     //调用拷贝构造函数
*/
MyString::MyString(const MyString& other)
{
    int len = strlen(other.m_data);
    m_data = new char[len + 1];
    strcpy(m_data, other.m_data);
}

/**
* @brief 赋值操作符重载,解决浅拷贝出现的内存泄露问题,调用形式:
* MyString str1 = "China1";   //调用普通构造函数
* MyString str2 = "China2";   //调用普通构造函数
* str1 = str2;     //调用赋值操作符重载
* @return 返回对象的应用,可以实现连等式
*/
MyString& MyString::operator=(const MyString& other)
{
    //如果自己赋值给自己
    if (this == &other) 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;
}

猜你喜欢

转载自blog.csdn.net/hhhuang1991/article/details/79830240