Thursday 25 April 2013

The following shows a concatenation operator for the string class:
#include <iostream.h>
#include <string.h>
class string {
private:
char *str;
public:
constructors and destructors as before
string operator+ (const string& rhs) const
{
char *s;
// create a new C style string holding
// the concatenated text
s = new char [strlen(str)+strlen(rhs.str)+1];
strcpy(s,str);
strcat(s,rhs.str);
// create a new `string', initialising it with the C
// style string
string newstring(s);
// delete the C style string, no longer needed
delete [] s;
// return a copy of the newly created string
return newstring;
}
void print() const
{
cout << str;
}

No comments:

Post a Comment