C String類的實現

2021-05-21 18:17:13 字數 1665 閱讀 5071

//**參考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_data=0;

else

m_data = new char[strlen(str)+1];

strcpy(m_data,str);

inline string::string(const string& other)

if(!other.m_data) m_data=0;

else

m_data=new char[strlen(other.m_data)+1];

strcpy(m_data,other.m_data);

inline string& string::operator=(const string& other)

if (this!=&other)

delete m_data;

if(!other.m_data) m_data=0;

else

m_data = new char[strlen(other.m_data)+1];

strcpy(m_data,other.m_data);

return *this;

inline string string::operator+(const string &other)const

string newstring;

if(!other.m_data)

newstring = *this;

else if(!m_data)

newstring = other;

else

newstring.m_data = new char[strlen(m_data)+strlen(other.m_data)+1];

strcpy(newstring.m_data,m_data);

strcat(newstring.m_data,other.m_data);

return newstring;

inline bool string::operator==(const string &s)    

if ( strlen(s.m_data) != strlen(m_data) )

return false;

return strcmp(m_data,s.m_data)?false:true;

inline char& string::operator(unsigned int e)

if (e>=0&&e<=strlen(m_data))

return m_data[e];

ostream& operator<<(ostream& os,string& str)

os << str.m_data;

return os;

void main()

string str1="hello!";

string str2="teacher!";

string str3 = str1+str2;

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...

C String類的實現

面試的時候被問及了string類的實現,結果沒寫好.就當是重新複習一下吧。下面的程式並沒有把string類的所有成員方法實現,只參考教程寫了大部分重要的成員函式。include includeusing namespace std class string string void private c...