Title: A simple implementation of the string class, this class is named MyString
Implementation ideas:
1 as long as the constructor executes successfully (where Pdata_ is not empty)
2 constructors can be constructed by char*, string constants
3 overloaded operator = ( return value mystring), implements copy constructor (deep copy, return value mystring&)
4 overloaded operator <<, so that it can be output through cout
5 implement string length, whether the string is an empty function
6 member variables save string using char* Pdata_, save string length using int length_
MyString.h
#pragma once#include <iostream>class mystring{public:mystring (const char * pStr = nullptr); MyString (const mystring& RHS); ~mystring (); bool Empty (); mystring& operator= (const mystring& RHS); MyString operator+ (const mystring& RHS); size_t size () { return length_;} Friend std::ostream& operator<< (std::ostream& os, const MyString &RHS);p Rivate:char *pdata_;size_t Length_;}; std::ostream& operator<< (std::ostream& os, const MyString &RHS);
MyString.cpp
#include "MyString.h" #include <cstring>mystring::mystring (const char *pstr) {if (nullptr = = pStr) {pdata_ = new char [1];*pdata_ = ' + '; length_ = 0;} Else{length_ = strlen (pStr);pD Ata_ = new Char[length_ + 1];strcpy (Pdata_, PSTR);}} Mystring::~mystring () {if (nullptr! = pdata_) {Delete Pdata_;pdata_ = Nullptr;length_ = 0;}} Mystring::mystring (const mystring& RHS) {if (nullptr = = Rhs.pdata_) {Pdata_ = new Char[1];*pdata_ = ' + '; length_ = 0;} Else{length_ = Rhs.length_;pdata_ = new Char[length_ + 1];strcpy (Pdata_, Rhs.pdata_);}} mystring& mystring::operator= (const mystring& RHS) {if (this = = &RHS) {return *this;} MyString newstring (RHS); char*temp = Newstring.pdata_;newstring.pdata_ = Pdata_;pdata_ = Temp;length_ = Rhs.length_;} MyString mystring::operator+ (const mystring& RHS) {MyString newstring;if (length_ > 0 | | rhs.length_ > 0) {char* t EMP = new Char[length_ + rhs.length_ + 1];strcpy (temp, pdata_); strcat (temp, rhs.pdata_);d elete Newstring.pdata_; Newstring.pdata_ = temp;Newstring.length_ = Length_ + rhs.length_;} return newstring;} BOOL Mystring::empty () {if (size () > 0) {return false;} Else{return true;}} std::ostream& operator<< (std::ostream& os, const MyString &RHS) {OS << rhs.pdata_;return os;}
main.cpp Test Code
#include <iostream> #include "MyString.h" using namespace Std;int Main () {MyString str;cout << "str =" << Str << endl;if (Str.empty ()) {cout << "str is empty" << Endl;} Else{cout << "str is not empty" << Endl;} str = "Fivestar"; cout << "str =" << str << endl;if (Str.empty ()) {cout << "str is empty" << Endl;} Else{cout << "str is not empty" << Endl;} MyString str2 = "Love a lot of girls"; cout << "str2.size () =" << str2.size () << endl;cout << str + STR2 << Endl;return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Simple implementation of C + + MyString class