c++中用STL封装了字符串类,但是这是不通用的。
实现字符串类,就是用面向对象的方式封装C语言对字符串的操作。
添加DTString.h文件:
1 #ifndef DTSTRING_H 2 #define DTSTRING_H 3 4 #include "Object.h" 5 6 namespace DTLib 7 { 8 9 class String : Object 10 { 11 protected: 12 char* m_str; 13 int m_length; 14 15 void init(const char* s); 16 public: 17 String(); 18 String(char c); 19 String(const char* s); 20 String(const String& s); 21 22 int length() const; 23 const char* str() const; 24 25 bool operator == (const String& s) const; 26 bool operator == (const char* s) const; 27 28 bool operator != (const String& s) const; 29 bool operator != (const char* s) const; 30 31 bool operator > (const String& s) const; 32 bool operator > (const char* s) const; 33 34 bool operator < (const String& s) const; 35 bool operator < (const char* s) const; 36 37 bool operator >= (const String& s) const; 38 bool operator >= (const char* s) const; 39 40 bool operator <= (const String& s) const; 41 bool operator <= (const char* s) const; 42 43 String operator + (const String& s) const; 44 String operator + (const char* s) const; 45 String operator += (const String& s); 46 String operator += (const char* s); 47 48 String& operator = (const String& s); 49 String& operator = (const char* s); 50 String& operator = (char c); 51 52 ~String(); 53 }; 54 55 } 56 57 58 #endif // DTSTRING_H
添加DTString.cpp文件:
1 #include <cstring> 2 #include <cstdlib> 3 #include "DTString.h" 4 #include "Exception.h" 5 6 using namespace std; 7 8 namespace DTLib 9 { 10 11 void String::init(const char* s) 12 { 13 m_str = strdup(s); 14 15 if( m_str ) 16 { 17 m_length = strlen(m_str); 18 } 19 else 20 { 21 THROW_EXCEPTION(NoEnoughMemoryException, "No memory to create string object ..."); 22 } 23 } 24 25 String::String() 26 { 27 init(""); 28 } 29 30 String::String(const char* s) 31 { 32 init(s ? s : ""); //空指针就转换成空字符串 33 } 34 35 String::String(const String& s) 36 { 37 init(s.m_str); 38 } 39 40 String::String(char c) 41 { 42 char s[] = {c, '