自定義string類

2021-09-25 11:36:43 字數 1624 閱讀 8259

//所需知識點:

//strcpy(arg1,arg2)//會把arg2的內容賦值給arg1,直到'\0'為止,複製結束後會在arg1後加乙個'\0';

//strlen();//返回字串長度,只會返回『\0』前字串的長度,如"123\0qweqr" 返回值為3

//std::cin;//遇到空格或回車符就結束輸入,遇到回車或eof會讀入

//std::cout//遇到\0結束

class cstring

cstring(const char*str)//建構函式

; //strcpy(m_data, '\0');

} else

}cstring(const cstring&str)//拷貝構造

; }

else

}cstring(cstring&&str) noexcept//移動構造

~cstring() }

public://工具函式

const char *cstr()

size_t size()

//操作符過載

public://只能定義為非成員函式

//輸入輸出運算子只能定義為非成員函式

friend std::ostream & operator <<(std::ostream&out, const cstring &s);

friend std::istream& operator>>(std::istream&in, cstring &s);

public://只能定義為成員函式

//賦值運算子必須定義為成員函式

cstring& operator =(const cstring& str)

public://兩者皆可

//通常情況下把算術運算子和關係運算子定義為非成員函式

friend cstring operator + (const cstring&v1, const cstring&v2);

friend bool operator == (const cstring&v1, const cstring&v2);

//復合運算子一般定義為成員函式

cstring & operator += (const cstring&s)

//下標成員函式

char& operator(size_t n)

//*/*cstring &operator * ()

*/ //& //編譯器會預設生成

//->

private:

char * m_data;

};std::ostream & operator <<(std::ostream&out, const cstring &s)

std::istream& operator>>(std::istream&in, cstring &s)

else

s.m_data = nullptr;

return in;

} cstring operator + (const cstring&v1, const cstring&v2)

bool operator ==(const cstring&v1, const cstring&v2)

自定義string類

在學習c 過程中,相比起使用char 或者是char陣列,使用 string 類對字串進行操作要方便快速很多。string 並不是c 的基本資料型別,它實際上是乙個類,那麼這個類具體是怎麼實現對字串的操作的呢?如何去自定義乙個類去實現string類同樣的效果呢?首先,先列舉一些 string 類可以...

c 自定義string類

1.標頭檔案部分 define crt secure no warnings pragma once include includeusing namespace std class mystring 2.函式定義部分 include mystring.h mystring mystring mys...

C 實現自定義string類

在一些c 筆試題裡,會有這樣一道題,那就是讓你自己實現乙個簡單的string類。自己在面試的時候就遇到過這個題。在這裡說一下自己是怎麼做的。主要包含一些基本的操作,建構函式 拷貝建構函式和析構函式。pragma once include using namespace std class mystr...