類String的建構函式、拷貝建構函式、解構函式和賦值運算子過載函式的實現
阿新 • • 發佈:2019-01-27
#include <iostream> using namespace std; class String { public: String(const char* str= NULL); String(const String& other); ~String(); String& operator = (const String &rhs); private: char* m_data; }; String::String(const char* str) { if(str == NULL) { m_data = new char[1]; *m_data = '\0'; } else { m_data = new char[strlen(str)+1]; strcpy(m_data,str); } } String::String(const String&other) { m_data = new char[strlen(other.m_data)+1]; strcpy(m_data,other.m_data); } /* 1,賦值前判斷是否是自賦值, 2,記憶體空間的準備 由於賦值前,物件已佔有一定大小記憶體,但是賦值物件所佔記憶體大小與 物件已佔的記憶體大小不一定一致; 先釋放物件已佔的記憶體,然後分配新記憶體。 3,賦值 */ String& String::operator=(const String& other) { if(this == &other) { return *this; } delete[]m_data; m_data = new char[strlen(other.m_data)+1]; strcpy(m_data,other.m_data); return *this; } String::~String() { if(m_data != NULL) { delete []m_data; m_data = NULL; } }