面试常常用到string类的实现,自己总结了一下:
#pragma once #include <iostream> #include <cassert> #include <iomanip> using namespace std; class string{ friend ostream& operator <<(ostream&,string&); friend istream& operator >>(istream&,string&); public: string(const char* str = NULL); //assignment constructor string(const string& str); ~string(){ delete [] m_data; } //get the length of string int size(){ return mystrlen(m_data); } //return substring 这里存在一些问题待改善 //当字符串的长度稍大一些时会出错; string substr(int pos); string substr(int pos,int len); //overload operator = string& operator =(const string& other); //overload operator + string operator +(const string& other)const; //overload operator += string& operator +=(const string& other); //overload operator == bool operator ==(const string& other)const; //overload operator [] char& operator [](unsigned int); private: char* m_data; };
cpp
#include "string.h" string::string(const char* str /* = NULL */) { if (!str) { m_data = new char[1]; *m_data = '