标准库String类

  1. 下面的程序并没有把String类的所有成员方法实现,只参考教程写了大部分重要的成员函数。
  2. [cpp] view plain copy
  3. #include<iostream>
  4. #include<iomanip>
  5. using namespace std;
  6. class String{
  7. friend ostream& operator<< (ostream&,String&);//重载<<运算符
  8. friend istream& operator>> (istream&,String&);//重载>>运算符
  9. public:
  10. String(const char* str=NULL); //赋值构造兼默认构造函数(char)
  11. String(const String &other); //拷贝构造函数(String)
  12. String& operator=(const String& other); //operator= //赋值函数
  13. String operator+(const String &other)const; //operator+
  14. bool operator==(const String&); //operator==
  15. char& operator[](unsigned int); //operator[]
  16. size_t size(){return strlen(m_data);};
  17. ~String(void) {delete[] m_data;} //析构
  18. private:
  19. char *m_data; // 用于保存字符串
  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. inline String::String(const String &other)
  30. {
  31. if(!other.m_data)m_data=0;//在类的成员函数内可以访问同种对象的私有成员(同种类则是友元关系)
  32. else
  33. {
  34. m_data=new char[strlen(other.m_data)+1];
  35. strcpy(m_data,other.m_data);
  36. }
  37. }
  38. inline String& String::operator=(const String& other)
  39. {
  40. if (this!=&other)
  41. {
  42. delete[] m_data;
  43. if(!other.m_data) m_data=0;
  44. else
  45. {
  46. m_data = new char[strlen(other.m_data)+1];
  47. strcpy(m_data,other.m_data);
  48. }
  49. }
  50. return *this;
  51. }
  52. inline String String::operator+(const String &other)const
  53. {
  54. String newString;
  55. if(!other.m_data)
  56. newString = *this;
  57. else if(!m_data)
  58. newString = other;
  59. else
  60. {
  61. newString.m_data = new char[strlen(m_data)+strlen(other.m_data)+1];
  62. strcpy(newString.m_data,m_data);
  63. strcat(newString.m_data,other.m_data);
  64. }
  65. return newString;
  66. }
  67. inline bool String::operator==(const String &s)
  68. {
  69. if ( strlen(s.m_data) != strlen(m_data) )
  70. return false;
  71. return strcmp(m_data,s.m_data)?false:true;
  72. }
  73. inline char& String::operator[](unsigned int e)
  74. {
  75. if (e>=0&&e<=strlen(m_data))
  76. return m_data[e];
  77. }
  78. ostream& operator<<(ostream& os,String& str)
  79. {
  80. os << str.m_data;
  81. return os;
  82. }
  83. istream &operator>>( istream &input, String &s )
  84. {
  85. char temp[ 255 ]; //用于存储输入流
  86. input>>setw(255)>>temp;
  87. s = temp; //使用赋值运算符
  88. return input; //使用return可以支持连续使用>>运算符
  89. }
  90. int main()
  91. {
  92. String str1="Aha!";
  93. String str2="My friend";
  94. String str3 = str1+str2;
  95. cout<<str3<<"/n"<<str3.size()<<endl;
  96. return 0;
  97. }





posted @ 2017-01-04 14:45  feizuzu  阅读(104)  评论(0编辑  收藏  举报