面試題:寫一個string類
阿新 • • 發佈:2019-02-19
一個string類主要包括建構函式、解構函式、拷貝建構函式和賦值建構函式
(1)建構函式需要注意的是:當建構函式引數為空時,string類中為char* pdata成員,因此在初始化成員列表中需開闢一個位元組的空間,並且賦初始值為‘\0’,因為在字串是以'\0'結尾的,會佔用一個位元組;
當建構函式引數為字串時,需注意字串的長度計算方法為strlen(ptr)+1
(2)解構函式需要注意:需使用delete[] pdata;
(3)拷貝建構函式需要注意:引數為引用,即為值本身傳遞,否則會導致拷貝建構函式呼叫拷貝建構函式,造成無限遞迴。
(4)賦值建構函式需要注意:返回值為引用,以便滿足像a = b = c這樣的連鎖賦值; 並且考慮異常安全性和自我賦值,採用copy &swap 方式
並且賦值建構函式需返回*this。具體可看effective C++
具體實現程式碼如下:
#ifndef _MY_STRING_H_ #define _MY_STRING_H_ #include <stdio.h> #include <string.h> class mystring_t { public: //建構函式 mystring_t() : m_pbuf(new char[1]) { *m_pbuf = '\0'; } mystring_t(const char *pbuf) : m_pbuf(new char[strlen(pbuf)+1]) { if (m_pbuf) { strcpy(m_pbuf, pbuf); } } //解構函式 ~mystring_t() { delete[] m_pbuf; m_pbuf = NULL; } //拷貝建構函式 mystring_t(const mystring_t& other) { mystring_t temp(other); //交換兩者 char *ptemp = temp.m_pbuf; temp.m_pbuf = m_pbuf; m_pbuf = ptemp; } //賦值建構函式 mystring_t& operator=(const mystring_t &str) { if (this != &str) { mystring_t temp(str); //交換兩者 char *ptemp = temp.m_pbuf; temp.m_pbuf = m_pbuf; m_pbuf = ptemp; } return *this; } //第二種寫法: //賦值建構函式 /*mystring_t& operator=(const mystring_t &str) { if (this != &str) { delete[] m_pbuf; m_pbuf = NULL; m_pbuf = new char[strlen(str.m_pbuf)+1]; strcpy(m_pbuf,str.m_pbuf); } return *this; }*/ private: char *m_pbuf; }; #endif