#include #include //for malloc, size_t, exit, EXIT_FAILURE #include //for strcpy, strlen #include "mystring.h" using namespace std; mystring::mystring(const mystring& another) //the copy constructor : n(another.n), p(static_cast(malloc(n + 1))) { if (p == 0) { cerr << "couldn't allocate " << n + 1 << " bytes\n"; exit(EXIT_FAILURE); } strcpy(p, another.p); } mystring::mystring(const char *s) : n(strlen(s)), p(static_cast(malloc(n + 1))) { if (p == 0) { cerr << "couldn't allocate " << n + 1 << " bytes\n"; exit(EXIT_FAILURE); } strcpy(p, s); } mystring& mystring::operator=(const mystring& another) { if (&another != this) { free(p); n = another.n; p = static_cast(malloc(n + 1)); if (p == 0) { cerr << "couldn't allocate " << n + 1 << " bytes\n"; exit(EXIT_FAILURE); } strcpy(p, another.p); } return *this; } mystring& mystring::operator=(const char *s) { free(p); n = strlen(s); p = static_cast(malloc(n + 1)); if (p == 0) { cerr << "couldn't allocate " << n + 1 << " bytes\n"; exit(EXIT_FAILURE); } strcpy(p, s); return *this; } char& mystring::operator[](size_t i) { if (i > n) { cerr << "Subscript " << i << " must be in range 0 to " << n << " inclusive.\n"; exit(EXIT_FAILURE); } return p[i]; } const char& mystring::operator[](size_t i) const { if (i > n) { cerr << "Subscript " << i << " must be in range 0 to " << n << " inclusive.\n"; exit(EXIT_FAILURE); } return p[i]; }