String

来源:互联网 发布:大猩猩和人杂交知乎 编辑:程序博客网 时间:2024/06/06 04:39
#pragma once#include <iostream>using namespace std;// strcpy 复制的时候将'\0'也复制过去了// strcat 复制的时候只要2个字符串的长度+1等于第一个字符串的空间就行class MyString{public:MyString(const char* pStr = NULL);MyString(const MyString& str);~MyString();public:bool operator==(const MyString& str);bool operator!=(const MyString& str);char &operator[](int iIndex);const char &operator[](int iIndex) const;public:MyString& operator=(const char *pStr);MyString& operator=(const MyString& str);MyString& operator+=(const MyString& str);MyString& operator+=(const char *pStr);public:friend ostream& operator<<(ostream& os, const MyString&str);private:char *m_pStr;};#include "StdAfx.h"#include "MyString.h"MyString::MyString(const char* pStr){if (pStr == NULL){m_pStr = new char[1];m_pStr[0] = '\0';}else{size_t iLen = strlen(pStr) + 1;m_pStr = new char[iLen];strcpy(m_pStr, pStr);}}MyString::MyString(const MyString& str) : m_pStr(NULL){operator=(str);}MyString::~MyString(){delete [] m_pStr;}bool MyString::operator==(const MyString& str){return (!strcmp(m_pStr, str.m_pStr));}bool MyString::operator!=(const MyString& str){return (!operator==(str));}char & MyString::operator[](int iIndex){return m_pStr[iIndex];}const char & MyString::operator[](int iIndex) const{return m_pStr[iIndex];}MyString& MyString::operator=(const char *pStr){if (pStr != NULL){delete [] m_pStr;size_t iLen = strlen(pStr) + 1;m_pStr = new char[iLen];strcpy(m_pStr, pStr);}return (*this);}MyString& MyString::operator=(const MyString& str){if (this != &str){operator=(str.m_pStr);}return (*this);}MyString& MyString::operator+=(const MyString& str){operator+=(str.m_pStr);return (*this);}MyString& MyString::operator+=(const char *pStr){if (pStr != NULL){char *pTemp = m_pStr;size_t iLen = strlen(pTemp) + strlen(pStr) + 1;m_pStr = new char[iLen];strcpy(m_pStr, pTemp);strcat(m_pStr, pStr);delete [] pTemp;}return (*this);}ostream& operator<<(ostream& os, const MyString&str){os << str.m_pStr;return os;}

原创粉丝点击