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;
}