复现String类(持续更新)
作者:互联网
2020/1/13
#ifndef __MYSTRING__ #define __MYSTRING__ #include <cstring> #include <iostream> using namespace std; class mystring { public: mystring(const char * cstr = 0); mystring(const mystring& str); //拷贝构造 mystring& operator = (const mystring& str); ~mystring(); char * get_c_str() const { return m_data; } private: char * m_data; }; inline mystring::mystring(const char * cstr) { if (cstr) { m_data = new char[strlen(cstr) + 1]; strcpy(m_data, cstr); } else { m_data = new char[1]; *m_data = '\0'; } } inline mystring::~mystring() { delete[] m_data; } inline mystring::mystring(const mystring& str) { m_data = new char[strlen(str.m_data) + 1]; strcpy(m_data, str.m_data); } inline mystring& mystring::operator = (const mystring& str) { if (this == &str) { return *this; } delete[] m_data; m_data = new char[strlen(str.m_data) + 1]; strcpy(m_data, str.m_data); return *this; } ostream& operator<<(ostream& os, const mystring& str) { os << str.get_c_str(); return os; } #endif // !__MYSTRING__
标签:const,String,更新,char,复现,str,cstr,mystring,data 来源: https://www.cnblogs.com/xiangqi/p/14273971.html