V
String
class, which — while having minimal functionality —
illustrates the use of and need for the canonical form.
.h file
for the class (note the use of the mystring
namespace again):
#ifndef MYSTRING_H #define MYSTRING_H #include <iostream> namespace mystring { class string { friend std::ostream &operator <<(std::ostream &os, const string &s); friend string operator +(const string &s1, const string &s2); public: string(const char *cs=""); string(const string &s); ~string(); string &operator =(const string &rhs); char &operator [](int index); string &operator +=(const string &s); int length() const; void clear(); private: char *cs; }; } #endifI've also supplied a string_Exception class and an app for testing your class (it is also the test driver in Codelab). Finally, I captured the expected output — you can see it in
mystring_app.stdout
.
std::string
class, the file names prove a bit more problematic; there
is actually a string.h
already... it's the C library for C-style strings — which if you recall is then wrapped by the
cstring
C++ library header. As such, please name your files with a my
prefix, i.e., mystring.h
,
mystring.cpp
and mystring_app.cpp
.
string(const char *cs="")
constructor allows one to create a String
from
C-string (and "..." literals, which are of type const char *
— i.e., C-strings).
cs
buffer are performed using the C-string functions you wrote in lab 4.2.
cs
data member (i.e., the pointer to the C-string buffer) is pointing to
a sufficiently sized buffer.
+=
and +
operators.
string(const char *)
constructor as an example:
strcpy
(this needs to be done in the
body of the constructor; there is no way to work it into the member intialization list)
string::string(const char *cs) : cs(new char[strlen(cs)+1) { // the +1 is for the null terminator
+=
operator (you should be
coding the +
operator using the +=
operator as shown in class): in those three cases the source buffer (i.e.,
the C-string to be copied, assigned, or concatenated) will be the cs
data member of another String
object.