C++ 笔试题 string类

mystring.h
#pragma once
#include <iostream>

class MyString
{
public:
    MyString(const char *str=NULL);
    ~MyString();
    MyString(const MyString &other);
    MyString &operator=(const MyString &other);
private:
    char *m_str;
};
mystring.cpp
#include "mystring.h"

MyString::MyString(const char *str)
{
    if (str)
    {
        m_str = new char[strlen(str)+1];
        strcpy(m_str, str);
    }
    else
    {
        m_str = new char[1];
        *m_str = '\0';
    }
}

MyString::~MyString()
{
    if(m_str)
    {
        delete [] m_str;
        m_str = NULL;
    }
}

MyString::MyString(const MyString &other)
{
    if (m_str)
    {
        delete [] m_str;
        m_str = NULL;
    }
    m_str = new char[strlen(other.m_str)+1];
    strcpy(m_str, other.m_str);
}

MyString &MyString::operator=(const MyString &other)
{
    if(this != &other) //检查自赋值
    {
       if (m_str)
       {
           delete [] m_str;
           m_str = NULL;
       }
       m_str = new char[strlen(other.m_str)+1];
       strcpy(m_str, other.m_str);
    }
    return *this;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容