// header file str.h for toy C++ strings package
#include <string.h> // for C library string functions
class ostream; // so we can declare output of strings
class string {
public:
string();
string(char *);
void append(char *);
const char* str() const;
string operator+(const string&) const;
const string& operator=(const string&);
const string& operator=(const char*);
friend ostream& operator<<(ostream&, const string&);
friend istream& operator>>(istream&, string&);
private:
char *data;
size_t size;
};
inline string::string() { size = 0; data = NULL; }
inline const char* string::str() const { return data; }
ostream& operator<<(ostream&, const string&);
istream& operator>>(istream&, string&);
Code Example B-2 is an implementation file str.cc of the string class functions.
//******************* str.cc *******************
// implementation for toy C++ strings package
#include <iostream.h>
#include "str.h"
string::string(char *aStr)
{
if (aStr == NULL)
size = 0;
else
size = strlen(aStr);
if (size == 0)
data = NULL;
else {
data = new char [size+1];
strcpy(data, aStr);
}
void string::append(char *app)
size_t appsize = app ? strlen(app) : 0;
char *holder = new char [size + appsize + 1];
if (size)
strcpy(holder, data);
holder[0] = 0;
if (app) {
strcpy(&holder[size], app);
size += appsize;
delete [] data;
data = holder;
string string::operator+(const string& second) const
string temp;
temp.data = new char[size + second.size + 1];
strcpy(temp.data, data);
temp.data[0] = 0;
if (second.size)
strcpy(&temp.data[size], second.data);
temp.size = size + second.size;
return temp;
const string& string::operator=(const string& second)
if (this == &second)
return *this; // in case string = string
if (second.size) {
data = new char[second.size+1];
size = second.size;
strcpy(data, second.data);
return *this;
const string& string::operator=(const char* str)
if (str && str[0]) {
size = strlen(str);
data = new char[size+1];
strcpy(data, str);
ostream& operator<< (ostream& ostr, const string& output)
return ostr << output.data;
istream& operator>> (istream& istr, string& input)
const int maxline = 256;
char holder[maxline];
istr.get(holder, maxline, '\n');
input = holder;
return istr;