自己实现的 string 类。
- #include<iostream>
- using namespace std;
- class string
- {
- friend ostream &operator<<(ostream &, string &) ;
- public:
- string(const char *str = NULL);
- string(const string &from);
- string &operator=(const string &other);
- string operator+(const string &rhs) const;
- bool operator==(const string &rhs);
- char &operator[](unsigned int n);
- size_t size(){return strlen(m_data);}
- ~string(){delete m_data;};
- 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 &from)
- {
- if(!from.m_data){
- m_data = 0;
- }
- else{
- m_data = new char[strlen(from.m_data) + 1];
- strcpy(m_data, from.m_data);
- }
- }
- inline 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 &rhs) const
- {
- string newString;
- if(!other.m_data){
- newString = *this;
- }
- else if(!m_data){
- newString = rhs;
- }
- else{
- newString = new char[strlen(m_data)+ strlen(rhs.m_data) + 1];
- strcpy(newString.m_data, m_data);
- strcat(newString.m_data, rhs.m_data);
- }
- return newString;
- }
- inline bool string::operator==(const string &rhs)
- {
- if(strlen(m_data) != strlen(rhs.m_data)){
- return false;
- }
- else{
- return strcmp(m_data, rhs.m_data)?false:true;
- }
- }
- inline char &string::operator[](unsigned int n)
- {
- if(n >= 0 && n <= strlen(m_data)){
- return m_data[n];
- }
- }
- ostream &operator<<(ostream &os, string &str)
- {
- os<<str.m_data;
- return os;
- }
有不完善的地方,将继续补充。