apstring - / * / Revised: January 13, 1998, <= and >=...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
// ******************************************************************* // Revised: January 13, 1998, <= and >= redefined using ! and < // operator += now takes constant // amortized time for adding one char // // Revised: November 19, 1998, replaced assert with exit: operator[] // changed operator >> and getline // so no limit on size of strings read // // APCS string class IMPLEMENTATION // // see apstring.h for complete documentation of functions // // string class consistent with a subset of the standard C++ string class // as defined in the draft ANSI standard // ******************************************************************* / #include <string.h> #include <assert.h> #include <stdlib.h> #include <ctype.h> #include "apstring.h" # const int npos = -1; c apstring::apstring() // postcondition: string is empty { myLength = 0; myCapacity = 1; myCstring = new char[myCapacity]; myCstring[0] = '\0'; // make c-style string zero length } apstring::apstring(const char * s) //description: constructs a string object from a literal string // such as "abcd" //precondition: s is '\0'-terminated string as used in C //postcondition: copy of s has been constructed { assert (s != 0); // C-string not NULL? myLength = strlen(s); myCapacity = myLength + 1; // make room for '\0' myCstring = new char[myCapacity]; strcpy(myCstring,s); } //description: copy constructor //postcondition: copy of str has been constructed { myLength = str.length(); myCapacity = myLength + 1; myCstring = new char[myCapacity]; strcpy(myCstring,str.myCstring); }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
} apstring::~apstring() //description: destructor //postcondition: string is destroyed { delete[] myCstring; // free memory } //postcondition: normal assignment via copying has been performed { if (this != &rhs) // check aliasing { if (myCapacity < rhs.length() + 1) // more memory needed? { delete[] myCstring; // delete old string myCapacity = rhs.length() + 1; // add 1 for '\0' myCstring = new char[myCapacity]; } myLength = rhs.length(); strcpy(myCstring,rhs.myCstring); } return *this; } //description: assignment from literal string such as "abcd" //precondition: s is '\0'-terminated string as used in C
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 7

apstring - / * / Revised: January 13, 1998, &lt;= and &gt;=...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online