C++面試或者筆試的時候經常遇到這樣一個問題,就是自己實現一個string類。
本人總結自己的面試經驗以及參考網上各位網友的總結,總得來說常見的主要實現的包括以下幾個方面(如有不如,歡迎補充)
常見:普通的構造函數、拷貝構造函數、析構函數、字符串的鏈接即‘+’號運算符重載、字符串賦值即‘=’號運算符重載、字符串是否相等即‘==’號運算符重載、獲取字符串長度
不常見:輸入‘>>’重載、輸出‘<<'重載
StringRealiza.h
1 #pragma once 2 3 #include <iostream> 4 5 class StringRealize 6 { 7 friend std::ostream& operator<<(std::ostream& os, const StringRealize& str);//輸出符重載 8 friend std::ostream& operator>>(std::ostream& os, const StringRealize& str);//輸入符重載 9 10 public: 11 StringRealize(const char *str = NULL);//普通構造函數 12 StringRealize(const StringRealize& str);//拷貝構造函數 13 ~StringRealize(void);//析構函數 14 15 StringRealize& operator=(const StringRealize& str);//賦值運算符'='號重載 16 StringRealize operator+(const StringRealize& str);//鏈接字符串‘+’號重載 17 bool operator==(const StringRealize& str);//等號運算符‘==’號重載 18 19 int getLength(void);//獲取字符串的長度 20 private: 21 char *m_data;//用於保存字符串 22 };
StringRealiza.cpp
1 #include "StringRealize.h" 2 3 //普通構造函數 4 StringRealize::StringRealize(const char *str) 5 { 6 if (str == NULL) 7 { 8 this->m_data = NULL; 9 } 10 else 11 { 12 this->m_data = new char[strlen(str) + 1]; 13 strcpy(this->m_data,str); 14 } 15 } 16 17 //拷貝構造函數 18 StringRealize::StringRealize(const StringRealize& str) 19 { 20 if (str.m_data == NULL) 21 { 22 this->m_data = NULL; 23 } 24 else 25 { 26 this->m_data = new char[strlen(str.m_data) + 1]; 27 strcpy(this->m_data,str.m_data); 28 } 29 } 30 31 //析構函數 32 StringRealize::~StringRealize(void) 33 { 34 if (this->m_data) 35 { 36 delete[] this->m_data; 37 this->m_data = NULL; 38 } 39 } 40 41 //賦值運算符'='號重載 42 StringRealize& StringRealize::operator=(const StringRealize& str) 43 { 44 if (this != &str) 45 { 46 delete[] this->m_data; 47 this->m_data = NULL; 48 49 if (str.m_data == NULL) 50 { 51 this->m_data = NULL; 52 } 53 else 54 { 55 this->m_data = new char[strlen(str.m_data) + 1]; 56 strcpy(this->m_data,str.m_data); 57 } 58 } 59 60 return *this; 61 } 62 63 //鏈接字符串‘+’號重載 64 StringRealize StringRealize::operator+(const StringRealize& str) 65 { 66 StringRealize newString; 67 if (str.m_data == NULL) 68 { 69 return *this; 70 } 71 else if (this->m_data == NULL) 72 { 73 newString = str; 74 } 75 else 76 { 77 newString.m_data = new char[strlen(str.m_data) + strlen(this->m_data) + 1]; 78 strcpy(newString.m_data,this->m_data); 79 strcpy(newString.m_data,str.m_data); 80 } 81 82 return newString; 83 } 84 85 //等號運算符‘==’號重載 86 bool StringRealize::operator==(const StringRealize& str) 87 { 88 if (strlen(this->m_data) != strlen(str.m_data) ) 89 { 90 return false; 91 } 92 else 93 { 94 return strcmp( this->m_data, str.m_data ) ? false : true; 95 } 96 97 } 98 99 //獲取字符串的長度 100 int StringRealize::getLength() 101 { 102 return strlen(this->m_data); 103 } 104 105 //輸出符重載 106 std::ostream& operator<<(std::ostream& os, const StringRealize& str) 107 { 108 os<<str.m_data; 109 return os; 110 } 111 112 //輸入符重載 113 std::ostream& operator>>(std::ostream& os, const StringRealize& str) 114 { 115 os>>str.m_data; 116 return os; 117 }