C String類的實現

2021-10-05 09:22:33 字數 3290 閱讀 7752

京東一面 開始面試官就讓自己實現乙個string類,方法寫出基本的就可以,沒告訴具體寫什麼,可能是由於時間原因(一共面了30min),我寫了建構函式以及賦值構造,析構,面試官就讓我停止了。

底層主要是借助字元陣列來實現

class

string

;

string::

string()

string::

string

(char

* str)

string::

string

(const string& other)

string::

~string()

string& string::

operator=(

char

* str)

string& string::

operator=(

const string& other)

delete

str_;

int len =

strlen

(other.str_)+1

; str_ =

newchar

[len]

;memset

(str_,

0, len)

;strcpy

(str_, other.str_)

;return

*this;}

char

& string::

operator

(unsigned

int index)

return

const_cast

<

char

&>

(static_cast

<

const string&

>(*

this

)[index]);

}const

char

& string::

operator

(unsigned

int index)

const

return str_[index];}

string operator+(

const string& s1,

const string & s2)

string& string::

operator+=

(const string & s)

bool string::

operator==(

const string& s)

istream&

operator

>>

(istream& in, string& s)

ostream&

operator

<<

(ostream& out,

const string& s)

int

main()

輸出結果:

測試建構函式

不傳參:

不傳參:1

字元陣列引數:hello

string 型別引數:hello

測試賦值建構函式

字元陣列引數:hello

string型別引數:hello

測試下標運算子

在字串長度範圍內:h

不在字串長度範圍內:o

測試+:

hellohello

測試+=:

hellohello

測試==

10

#include

using

namespace std;

class

string

;string::

string()

string::

string

(char

* str)

string::

string

(const string& other)

string::

~string()

string& string::

operator=(

char

* str)

string& string::

operator=(

const string& other)

delete

str_;

int len =

strlen

(other.str_)+1

; str_ =

newchar

[len]

;memset

(str_,

0, len)

;strcpy

(str_, other.str_)

;return

*this;}

char

& string::

operator

(unsigned

int index)

return

const_cast

<

char

&>

(static_cast

<

const string&

>(*

this

)[index]);

}const

char

& string::

operator

(unsigned

int index)

const

return str_[index];}

string operator+(

const string& s1,

const string & s2)

string& string::

operator+=

(const string & s)

bool string::

operator==(

const string& s)

istream&

operator

>>

(istream& in, string& s)

ostream&

operator

<<

(ostream& out,

const string& s)

intmain()

C String類的實現

參考c primer.string類的實現,清翔兔 06,jan.include using namespace std class string string void private char m data inline string string const char str if str m...

C String類的實現

include using namespace std class string string void private char m data inline string string const char str inline string string const string other i...

c string類的實現

友元函式可以轉換左右運算元的順序,而成員函式必須保證左運算元string已經處於正確的形式。include include includeusing namespace std class string friend const string operator const string other1...