string 类的实现
生活随笔
收集整理的這篇文章主要介紹了
string 类的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. #include<iostream>
2. #include<iomanip>
3. using namespace std;
4.
5. class String{
6. friend ostream& operator<< (ostream&,String&);//重載<<運算符
7. friend istream& operator>> (istream&,String&);//重載>>運算符
8. public:
9. String(const char* str=NULL); //賦值構造兼默認構造函數(char)
10. String(const String &other); //賦值構造函數(String)
11. String& operator=(const String& other); //operator=
12. String operator+(const String &other)const; //operator+
13. bool operator==(const String&); //operator==
14. char& operator[](unsigned int); //operator[]
15. size_t size(){return strlen(m_data);};
16. ~String(void) {delete[] m_data;}
17. private:
18. char *m_data; // 用于保存字符串
19. };
20.
21. inline String::String(const char* str)
22. {
23. if(!str)m_data=0; //聲明為inline函數,則該函數在程序中被執行時是語句直接替換,而不是被調用
24. else {
25. m_data=new char[strlen(str)+1];
26. strcpy(m_data,str);
27. }
28. }
29.
30. inline String::String(const String &other)
31. {
32. if(!other.m_data)m_data=0;//在類的成員函數內可以訪問同種對象的私有成員(同種類則是友元關系)
33. else
34. {
35. m_data=new char[strlen(other.m_data)+1];
36. strcpy(m_data,other.m_data);
37. }
38. }
39.
40. inline String& String::operator=(const String& other)
41. {
42. if (this!=&other)
43. {
44. delete[] m_data;
45. if(!other.m_data) m_data=0;
46. else
47. {
48. m_data = new char[strlen(other.m_data)+1];
49. strcpy(m_data,other.m_data);
50. }
51. }
52. return *this;
53. }
54. inline String String::operator+(const String &other)const
55. {
56. String newString;
57. if(!other.m_data)
58. newString = *this;
59. else if(!m_data)
60. newString = other;
61. else
62. {
63. newString.m_data = new char[strlen(m_data)+strlen(other.m_data)+1];
64. strcpy(newString.m_data,m_data);
65. strcat(newString.m_data,other.m_data);
66. }
67. return newString;
68. }
69.
70. inline bool String::operator==(const String &s)
71. {
72. if ( strlen(s.m_data) != strlen(m_data) )
73. return false;
74. return strcmp(m_data,s.m_data)?false:true;
75. }
76.
77. inline char& String::operator[](unsigned int e)
78. {
79. if (e>=0&&e<=strlen(m_data))
80. return m_data[e];
81. }
82.
83. ostream& operator<<(ostream& os,String& str)
84. {
85. os << str.m_data;
86. return os;
87. }
88.
89. istream &operator>>( istream &input, String &s )
90. {
91. char temp[ 255 ]; //用于存儲輸入流
92. input>>setw(255)>>temp;
93. s = temp; //使用賦值運算符
94. return input; //使用return可以支持連續使用>>運算符
95. }
?
轉載于:https://www.cnblogs.com/NeilZhang/p/5312196.html
總結
以上是生活随笔為你收集整理的string 类的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android应用安全开发之浅谈加密算法
- 下一篇: Python~第三方模块