string類的模擬實現

2021-10-21 14:14:48 字數 1197 閱讀 2392

1.淺拷貝:

(1)也稱位拷貝,編譯器只是將物件中的值拷貝過來。如果物件中管理資源,最後就會導致多個物件共享同乙份資源,當乙個物件銷毀時就會將該資源釋放掉,而此時另一些物件不知道該資源已經被釋放,以為還有效,所以當繼續對資源進行操作時,就會發生發生了訪問違規。

(2)如果string類中沒有顯式定義其拷貝建構函式與賦值運算子過載,此時編譯器會合成預設的,當用s1構造s2時,編譯器會呼叫預設的拷貝構造。最終導致的問題是,s1、s2共用同一塊記憶體空間,在釋放時同一塊空間被釋放多次而引起程式崩潰。

string s1

("hello bit!!!");

string s2

(s1)

;

2.深拷貝:

如果乙個類中涉及到資源的管理,其拷貝建構函式、賦值運算子過載以及析構函式必須要顯式給出。一般情況都是按照深拷貝方式提供。

//模擬實現string

namespace lhw

string()

:_str(new char[1])

*/string

(const

char

* str="")

//全預設 ""表示'\0'

:_str

(new

char

[strlen

(str)+1

])//拷貝構造(深拷貝)

string

(const string& s)

:_str

(new

char

[strlen

(s._str)+1

])//賦值運算子過載

string&

operator=(

const string& s)

return

*this;}

~string()

size_t size()

char

&operator

(size_t i)

const

char

*c_str()};}

模擬實現string類

include using namespace std include class string string string a 2 為什麼要用 優點在哪 string void print string operator const string a string operator const s...

模擬實現string類

在c 中,string其實就是將字串封裝起來的類,呼叫類中的成員函式可以完成對類內的字串進行增刪查改,並且將操作符過載,可以更直觀的操作字串,省去了c語言中很多麻煩的操作,有現成的成員函式供我們使用。舉乙個簡單的例子 在c語言中要在一串字串的尾部拼接另乙個字串,我們需要做的事情就是定義兩個字串,要使...

string類模擬實現

define crt secure no warnings include include using namespace std class string iterator end const iterator begin const const iterator end const 無參建構函式...