string類裡面主要包含構造,拷貝構造,析構,賦值,比較,字串相加,獲取長度及子串等方法。
#include
#include
using
namespace
std;
class string;
// 建構函式
string::string(char *str = null)
else
}//拷貝建構函式
string::string(const string &str)
//析構函式
string::~string()
// 字串連線
//這裡返回的不是引用,而是值
string string::operator+(const string &str)
//賦值函式
/*這裡為什麼返回物件的引用呢?原因有兩個:①允許進行連續賦值 ②防止返回物件(返回物件也可以進行連續賦值)的時候呼叫拷貝建構函式和析構函式導致不必要的開銷,降低賦值運算子等的效率。
對於第二點原因:如果用「值傳遞」的方式,雖然功能仍然正確,但由於return語句要把 *this拷貝到儲存返回值的外部儲存單元之中,增加了不必要的開銷,會降低賦值函式的效率。
因此,如果賦值運算子返回的是物件引用,那麼其不會呼叫類的拷貝建構函式,這是問題的關鍵所在!!
*/string& string::operation=(const
char * str)
delete m_data;
m_size = strlen(str);
m_data = new
char[m_size + 1];
strcpy(m_data, str);
return *this;
}//判斷是否相等
bool string::operation==(const
char *str)
//獲取長度
int string::length()
//求子字串[start,start+n-1]
string string::substr(int start, int n)
newstr.m_data[n] = '\0';
newstr.m_size = n;
return newstr;
}// 過載輸出
ostream & operator
<<(ostream &o, const string &str)
C string類簡單實現
include includeusing namespace std class mystring ostream operator ostream os,const mystring s mystring mystring length 0 cout default constructtion i...
c string類的簡單實現
本文只是實現string的一些簡單功能,實現建構函式 拷貝建構函式 賦值函式 析構函式這幾個非常重要的部分。因為string裡涉及動態記憶體的管理,這時就要求程式設計師自己實現這些函式進行深複製,即不止複製指標,需要連同記憶體的內容一起複製,析構函式釋放對應的記憶體。除了以上幾個個必須的函式,這裡還...
CString的簡單實現
注意事項 1 注意為結尾符 0 申請乙個位元組的空間 2 在拷貝建構函式和賦值函式中,注意使用深拷貝,而不是淺拷貝 3 過載輸入 輸出運算子 include includeusing namespace std class cstring cstring const cstring other cs...