类String的构造函数、析构函数和赋值函数
生活随笔
收集整理的這篇文章主要介紹了
类String的构造函数、析构函数和赋值函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、類String的原型為:
1 class String 2 { 3 public: 4 String(const char *str = NULL); //普通構造函數 5 6 ~String(void); //析構函數 7 8 String(const String &other); //拷貝構造函數 9 10 String & operator=(const String & other); //賦值函數 11 12 private: 13 char *m_pData; 14 };二、類String的普通構造函數
1 String::String(const char *str) 2 { 3 if(str == NULL) 4 { 5 m_pData = new char[1]; 6 *m_pData = '\0'; 7 } 8 else 9 { 10 int length = strlen(str); 11 m_pData = new char[length + 1]; 12 strcpy(m_pData, str); 13 } 14 }三、類String的析構函數
1 String::~String(void) 2 { 3 //由于m_pData是內部數據類型,也可以寫成 delete m_pData; 4 delete [] m_pData; 5 }四、類String的拷貝構造函數
1 String::String(const String &other) 2 { 3 int length = strlen(other.m_pData); 4 5 m_pData = new char[length + 1]; 6 7 strcpy(m_pData, other.m_pData); 8 }五、類String的賦值函數
1 String & String::operator=(const String &other) 2 { 3 if(this == &other) //檢查自賦值 4 return *this; 5 6 delete [] m_pData; //釋放原來的資源 7 8 int length = strlen(other.m_pData); //分配新的資源并分配控件 9 m_pData = new char[length + 1]; 10 strcpy(m_pData, other.m_pData); 11 12 return *this; //返回自身的引用 13 }?
轉載于:https://www.cnblogs.com/Dreamcaihao/archive/2013/05/21/3091662.html
總結
以上是生活随笔為你收集整理的类String的构造函数、析构函数和赋值函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通过用户模型,对数据库进行增删改查操作
- 下一篇: 英语之各类人群