header file, the function is mostly implicitly inline.
#ifndef mystring_h#define mystring_h#include <iostream> #include <string.h>class MYSTRING {friend Std::o stream& operator<< (Std::ostream &, const MyString &); friend std::istream& operator>> (std: : IStream &, MyString &);p ublic:mystring (): Content (new char[1]) {*content = '% ';} MyString (const char *STR): Content (new Char[strlen (str) + 1]) {strcpy_s (content, strlen (content), str);} MyString (const size_t sz, char &c); MyString (const MyString &MS): Content (new Char[ms.size () + 1]) {strcpy_s (content, strlen (content), ms.content);} mystring& operator= (const MyString &); ~mystring () {delete[] content;} void swap (MyString &rhs) {std::swap (content, rhs.content);} size_t size () const {return strlen (content);} Const char& operator[] (std::size_t N) const{if (n < strlen (content)) return content[n];} BOOL operator== (const MyString &RHS) {return strcmp (content, rhs.content);} BOOL Operator!= (const MyString &RHS) {return strCMP (content, rhs.content);} MyString operator+= (const MyString &RHS); MyString operator+ (const MyString &RHS) {*this + = Rhs;return *this;} Private:char *content;}; #endif
MyString.cpp
#include "myString.h" MyString & mystring::operator= (const myString &ms) {char *temp = Ms.content;delete Ms.content;content = Temp;return *this;} MyString mystring::operator+= (const MyString &RHS) {if (rhs.content = = nullptr) return *this;if (this = = &RHS) {MyS Tring copy (*this); return *this + = copy; }char *content_old = content;content = new Char[strlen (content) + strlen (rhs.content) + 1];strcpy_s (content, strlen (conte NT), content_old); strcat_s (content, strlen (content), rhs.content);d elete[] Content_old;return *this;} std::ostream& operator<< (std::ostream &os, const MyString &ms) {OS << ms.content << std:: Endl;return OS;} std::istream& operator>> (Std::istream &is, MyString &ms) {is >> ms.content;return are;}
Main function test
#include <iostream> #include "myString.h" using Std::cout; Using Std::cin; Using Std::endl;intmain () {MyString str1;cout << "Enter a string" << endl;cin >> str1;cout << str1 << Endl; MyString str2 ("test"), cout << str2 << endl;cout << str2[2] << endl;return 0;}
Implementing the C + + string class