C++類設計2(Class with pointer members)
阿新 • • 發佈:2017-06-01
delet images itl his per 復制代碼 復制 定義 行為
二 Class with pointer members(Class String)
1. 測試代碼(使用效果)
int main() { String s1(), String s2("hello"); //構造函數 String s3(s1); //拷貝構造 cout << s3 << endl; s3 = s2; //拷貝賦值 cout << s3 << endl; }
2 Big three(三種特殊函數)
class String { public: String(const char* cstr = 0); String(const String& str); //參數為相同類型對象的引用,拷貝構造 String& operator=(const String& str); //拷貝賦值 ~String() //析構函數 char* get_c_str() const{ return m_data; } private: char* m_data; };
2.1 ctor & dtor(構造與析構)
inline String::String(const char* cstr = 0) { if(cstr){ m_data = new char[strlen(cstr)+1]; strcpy(m_data,cstr); } else{ //未指定長度 m_data = new char[1]; *m_data = ‘\0‘; } } inline String::~String() { delete[] m_data; }
2.2 Class with pointer members必須有copy ctor(拷貝構造)和copy op(拷貝賦值)
深拷貝與淺拷貝
深拷貝:
inline String::String(const String& str){ m_data = new char[strlen(str.m_data) + 1]; //直接取得另一個對象的private數據 //可用友元解釋 strcpy(m_data, str.m_data); }
拷貝賦值函數:
思路:若右邊拷貝到左邊,步驟為 清空左邊;分配與右邊相同空間;完成拷貝。
inline String& String::operator=(const String& 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 }
總結:有指針變量的類,一定要重新其拷貝構造,拷貝賦值和析構函數!
C++類設計2(Class with pointer members)