Professional Documents
Culture Documents
Listing 5 Listing 6
A simple string class featuring constructors, C substitute for simple string class.
destructors, operator overloading, new, and delete. /* C substitute
// A simplified string class for simplified string class */
#include #include
#include #include
using namespace std; #include
class String { struct String {
private: char* data;
char* data; unsigned len;
unsigned len; };
public: #define length_String(s) ((s)->len)
String(); void StringConstructor(String* this) {
~String(); this->len = 0;
unsigned length() const; this->data = 0;
String& operator=(const char* s); }
}; void StringDestructor(String* this) {
inline unsigned String::length() const if (this->data != 0)
{ free(this->data);
return len; }
}; String operatorEquals_String_const_char_star(
String::String() { String* this, const char* s) {
len = 0; this->len = strlen(s);
data = 0; this->data = (char*) malloc(
} (this->len+1) * sizeof(char));
String::~String() { /*
if (data != 0) If char had a constructor, */
delete [] data; /* it would be have to be */
} /* called here. */
String& String::operator=(const char* s) { if (this->data == 0)
len = strlen(s); this->len = 0;
data = new char [ len+1 ]; else
if (data == 0) strcpy(this->data, s);
len = 0; return *this;
else }
strcpy(data, s); FILE*
return *this; operatorShiftLeft_ostream_unsigned(FILE*,
} unsigned);
void main() { void main() {
String s; String s;
s = “Hello world”; StringConstructor(&s);
cout operatorEquals_String_const_char_star(
< &s, “Hello world”);
< operatorShiftLeft_ostream_unsigned(stdout,
s.length(); length_String(&s));
} StringDestructor(&s);
}