又复习了一次C++,string类的实现。自己的基础还是太差了。不过像这样的知识,感觉不断的写,对编程还是有提升的。所以写成博客,希望能帮到像我一样的人,当然这很多内容借鉴来自于网上,若有类同,请宽恕!
C# Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
#include<iostream>
#include <stdlib.h> using namespace std; class CMystring { public: CMystring( const char *str = NULL); //构造函数 CMystring( const CMystring& str); //拷贝构造函数 CMystring& operator=( const CMystring& str); //拷贝构造函数 CMystring operator+( const CMystring& str); //加号操作。 bool operator==( const CMystring& str); //重载==号 ~CMystring(); //析构函数 void print() { cout<<m_pData<<endl; } private: char *m_pData; }; CMystring::CMystring( const char *str) { if (!str) //如果str等于0,则指针赋值为0; { this->m_pData = 0; cout<< "here..."<<endl; } else { this->m_pData = new char[strlen(str) + 1]; strcpy( this->m_pData,str); } cout << "CMystring..." << endl; } CMystring::CMystring( const CMystring& str) { if (!str.m_pData) { this->m_pData = 0; } else { this->m_pData = new char[(strlen(str.m_pData)) + 1]; strcpy( this->m_pData, str.m_pData); } } CMystring& CMystring:: operator=( const CMystring& str) { if ( this!=&str) { delete[] this->m_pData; if (!str.m_pData) { this->m_pData = 0; } else { this->m_pData = new char[strlen(str.m_pData) + 1]; strcpy( this->m_pData, str.m_pData); } } cout << "copy CMystring ..." << endl; return * this; } CMystring CMystring:: operator+( const CMystring& str) { CMystring newString; if (!str.m_pData) { newString = * this; } else if (! this->m_pData) { newString = str; } else { newString.m_pData = new char[strlen( this->m_pData) + strlen(str.m_pData) + 1]; strcpy(newString.m_pData, this->m_pData); strcat(newString.m_pData, str.m_pData); } cout<< "++"<<endl; return newString; } bool CMystring:: operator==( const CMystring& str) { if (strlen( this->m_pData)!=strlen(str.m_pData)) { return false; } else { return strcmp( this->m_pData, str.m_pData) ? false : true; } } CMystring::~CMystring() { if ( this->m_pData) { delete this->m_pData; this->m_pData = 0; } } int main() { CMystring a( "i love "); a.print(); CMystring b( "you !"); b.print(); CMystring c; c=a+b; c.print(); if (a==b) { cout<< "haha"<<endl; } else { cout<< "oho"<<endl; } getchar(); return 0; } |