1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
void addSong(CD* cd, String* title, String* length)
{
// Create new larger song array to hold one more song
Song** new_song_array = new Song* [cd->num_tracks + 1];
// Copy contents from old array
for (int i = 0; i < cd->num_tracks; i++)
{
new_song_array[i] = cd->song_array[i];
}
// Create new song, add it to new array to the end
Song* song = createSong(title, length);
new_song_array[num_tracks] = song;
// Update num_tracks
cd->num_tracks ++;
// delete old array, and replace with new one
delete[] (cd->song_array);
cd->song_array = new_song_array;
}
int main()
{
CD cd;
cd.artist = new String ("Artist");
// The following two lines are required to initialize variables
// to initial zero state (no songs added yet, so num_tracks = 0)
cd.num_tracks = 0;
cd.song_array = new Song*[cd.num_tracks];
// Add some songs
addSong(&cd, new String("Some Title"), new String ("4:20"));
addSong(&cd, new String("Other Title"), new String ("1:52"));
addSong(&cd, new String("Yet another Title"), new String ("2:02"));
// Just show the album details
for(int i = 0; i < cd.num_tracks; i++)
{
cout << i+1 << ". " << cd.song_array[i]->title->value
<< " " << cd.song_array[i]->length->value << endl;
}
}
|
1. Some Title 4:20
2. Other Title 1:52
3. Yet another Title 2:02 |