http://zhedahht.blog.163.com/blog/static/25411174200741543224391/
博客中第二种实现方法实在是精妙:
CMyString& CMyString::operator =(const CMyString &str) { if(this != &str) { CMyString strTemp(str); char* pTemp = strTemp.m_pData; strTemp.m_pData = m_pData; m_pData = pTemp; } return *this; }
然后自己手贱写了个模板字符串类,初衷是为了对付tchar的,但是无奈水平有限,输出的时候貌似就实现不了,当是练练C++了:
#include <iostream> #include <cstring> using namespace std; template<typename T> class CMyString { public: CMyString(); CMyString(const T* data); CMyString(const CMyString& other); CMyString& operator = (const CMyString& other); CMyString& operator = (const T* data); friend std::ostream& operator << <T> (std::ostream& os, const CMyString& str); const T* c_str() const; const size_t& size() const; ~CMyString(); public: T* m_data; size_t m_length; }; template<typename T> CMyString<T>::~CMyString() { if (m_data) { delete[] m_data; m_data = nullptr; m_length = 0; } } template<typename T> const size_t& CMyString<T>::size() const { return m_length; } template<typename T> CMyString<T>::CMyString() { m_data = nullptr; m_length = 0; } template<typename T> CMyString<T>::CMyString(const T* other) { if (other == nullptr) { m_data = nullptr; m_length = 0; } else { m_length = strlen(other); m_data = new T[m_length + 1]; strcpy_s(m_data, m_length + 1, other); } } template<typename T> CMyString<T>::CMyString(const CMyString<T>& other) { if (this == &other) return; m_length = other.size(); m_data = new T[m_length + 1]; strcpy_s(m_data, m_length + 1, other.m_data); } template<typename T> CMyString<T>& CMyString<T>::operator = (const CMyString<T>& other) { if (this != &other) { CMyString<T> cpy(other); T* temp = cpy.m_data; cpy.m_data = m_data; m_data = temp; size_t len = cpy.m_length; cpy.m_length = m_length; m_length = len; } return *this; } template<typename T> CMyString<T>& CMyString<T>::operator = (const T* data) { if (data) { if (m_data) { delete[] m_data; m_data = nullptr; m_length = 0; } m_length = strlen(data); m_data = new T[m_length + 1]; strcpy_s(m_data, m_length + 1, data); } return *this; } template<typename T> const T* CMyString<T>::c_str() const { return m_data; } template<typename T> std::ostream& operator << (std::ostream& os, const CMyString<T>& str) { os << str.c_str(); return os; } int main() { CMyString<char> s1("abc"); std::cout << s1 << endl; return 0; }