模擬實現了String類

2021-09-29 16:46:06 字數 2770 閱讀 1529

#define _crt_secure_no_warnings

#include

using

namespace std;

#include

class

string

string

(const

char

* str ="")

string

(const string& str)

:_str

(nullptr),

_size(0

),_capacity(0

)int

capacity()

intsize()

~string()

} string&

operator

=(string str)

//傳參是傳的值,這樣進來的時候就會執行一次拷貝構造

char

&operator

(size_t pos)

const

char

&operator

(size_t pos)

const

iterator begin()

iterator end()

const iterator begin()

const

const iterator end()

const

const_iterator cbegin()

const

const_iterator cend()

const

void

reserve

(size_t n)

}void

resize

(size_t sz,

char c =

'\0')if

(sz > _size)

//如果_size

_size = sz;

//如果sz < _size:更新_size,將最後一位變成'\0',但是並不刪除元素(並不釋放空間)

_str[_size]

='\0';}

const

char

*c_str()

const

void

insert

(size_t pos,

char c)

size_t end = _size +1;

while

(end > pos)

//從前往後移動元素

_str[pos]

= c;

//插入元素

++_size;

}void

insert

(size_t pos,

const

char

* c)

size_t end = _size + sz;

while

(end > pos + sz -1)

//從前往後賦值(移動元素

while

(*c)

//插入字串

_size +

= sz;

} string&

operator+=

(char c)

string&

operator+=

(const

char

* str)

string&

operator+=

(const string& str)

void

push_back

(char c)

void

(const

char

* str)

void

erase

(size_t pos,

int len)

// h e l l o x l \0 pos = 2 , len = 2 --> h e o x l \0

else

_size -

= len;}}

void

erase

(iterator it)

size_t find

(const

char

* str, size_t pos =0)

//abc abcde df abcd

if(begin ==

strlen

(str)

)//如果找到str的\0了就說明找到了

} _begin++

; _end = _begin;

begin =0;

//每次都要從str的開始位置開始找

}return npos;

//沒找到就返回int最大值

} size_t find

(char c, size_t pos =0)

}return npos;

}private

:char

* _str;

size_t _capacity;

size_t _size;

static

const size_t npos;};

const size_t string::npos =-1

;ostream&

operator

<<

(ostream& _cout,

const string& str)

*/return _cout;

}

模擬實現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 無參建構函式...