|
CMPT 212
Spring 1998
|
#include <stdlib.h>
#include <iostream.>
class rectangle {
public:
rectangle(); // default constructor.
~rectangle(); // destructor.
...
};
rectangle::rectangle() {
cout << "a new rectangle" << endl;
}
rectangle::~rectangle() {
cout << "one less rectangle" << endl;
}
int main() {
rectangle a;
rectangle * b = NULL;
cout << "one" << endl;
b = new rectangle;
cout << "two" << endl;
delete b;
cout << "three" << endl;
return 0;
}
a new rectangle
one
a new rectangle
two
one less rectangle
three
one less rectangle
class sentence {
public:
sentence();
sentence(const char * w);
sentence(const sentence& s);
~sentence();
int wordCount();
void clear();
boid appendWord(const char * w);
private:
char * words;
int count;
};
sentence::sentence() {
words = NULL;
count = 0;
}
sentence::sentence(const char * w) {
words = NULL;
count = 0;
appendWord(w);
}
sentence::sentence(const sentence& s) {
words = new char[strlen(s.words) + 1]
strcpy(words, s.words);
count = s.count;
}
sentence::~sentence() {
clear();
}
int sentence::wordCount() {
return count;
}
void sentence::clear() {
delete [] words;
words = NULL;
count = 0;
}
void sentence::appendWord(const char * w) {
if (words == NULL) {
words = new char[strlen(w) + 1];
strcpy(words, w);
count = 1;
}
else {
int wordsLen = strlen(words);
char * newWords = new char[wordsLen + 1 + strlen(w) + 1];
strcpy(newWords, words);
strcat(newWords, " ");
strcat(newWords, w);
delete [] words;
words = newWords;
count++;
}
}
Return to lecture notes index |
|
| This page is maintained by simpson@cs.sfu.ca. | Last updated on 6 Feb 1998. |