Update 11 Jan: Fixed date at top of page to actual date of the class.
C++ strings vs. C strings
C strings, as you recall, are just a null-terminated array of char:
/* These two do the same thing */ char str[] = "hello"; char str2[] = { 'h', 'e', 'l', 'l', 'o', '\0' }; C++ offers a better way of working with strings, which you will not need to use for this assignment (but which are good to know):
#include // New C++ string library int main() { string str = "Hello"; // string has a compare() method, analogous to strcmp if (str.compare("Hullo") < 0) { // We can modify and create strings in various ways string str2 = str.substr(0, 5); cout << str2 << endl; str.append(", world\n"); str.replace(str.find("Hello"), 5, "Hallo"); } // We can also get a (non-modifiable) C-style string // representation of the current object. const char * old_c_string = str.c_str(); cout << old_c_string; } Classes : better structs
Classes extend structs by coupling methods directly to the data. This allows us to model real-world objects the way I was babbling about in the first lecture. Consider the problem of modeling a car (for, say, a traffic simulation). In English, you might say:
A car is an object that has a position, a speed, a certain amount of gas, and a certain number of passengers. When you accelerate, the amount of gas goes down and the speed increases according to its mileage. When you brake, the speed decreases. When you park, the speed goes to zero.Classes allows us to express this design almost directly in code:
struct Point { int x, y; }; class Car { public: void accelerate(double factor); void brake(double factor); void park(); Point getPosition() const; // Example of selector void setPosition(Point pos); // Example of mutator private: Point position; double speed, gas; int passengers; }; How about the problem of modeling a CD collection? In English, one way to describe it is as follows:
A CD collection consists of a set of CDs. Each CD has an ordered set of songs. Each song has a name, running time, and an artist, which may be the same for every song on the disc (but is not in the case of movie soundtracks etc.)Can you write some classes that model a CD collection? Concentrate on operations you might like to perform on each class, not on the underlying representation: for example, adding, selecting, listing, etc. Don't feel you need to adhere strictly to the above English definition. Some relevant questions:
- What are the classes in our data?
- What should be public? What should be private?
- What should the types/profiles of each member (both data and function members) be?
Hint: you may find it useful to start with the simplest types, as above, where we started the Car definition by defining a Point.