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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
#include <iostream> #include <vector> #include <string> // Class representing a Music Track class MusicTrack { public: MusicTrack(const std::string& title) : title(title) {} std::string getTitle() const { return title; } private: std::string title; }; // Class representing the Music Player class MusicPlayer { public: void addTrack(const MusicTrack& track) { playlist.push_back(track); } void playTrack(int index) const { if (index < 0 || index >= playlist.size()) { std::cout << "Invalid track number.\n"; return; } std::cout << "Playing: " << playlist[index].getTitle() << "\n"; } void listTracks() const { std::cout << "Playlist:\n"; for (size_t i = 0; i < playlist.size(); ++i) { std::cout << i << ". " << playlist[i].getTitle() << "\n"; } } private: std::vector<MusicTrack> playlist; }; int main() { MusicPlayer player; // Adding some tracks to the playlist player.addTrack(MusicTrack("Song 1 - Artist A")); player.addTrack(MusicTrack("Song 2 - Artist B")); player.addTrack(MusicTrack("Song 3 - Artist C")); int choice; do { std::cout << "\nMusic Player Menu:\n"; std::cout << "1. List Tracks\n"; std::cout << "2. Play Track\n"; std::cout << "3. Exit\n"; std::cout << "Enter your choice: "; std::cin >> choice; switch (choice) { case 1: player.listTracks(); break; case 2: { int trackNumber; std::cout << "Enter track number to play: "; std::cin >> trackNumber; player.playTrack(trackNumber); break; } case 3: std::cout << "Exiting the music player.\n"; break; default: std::cout << "Invalid choice. Please try again.\n"; break; } } while (choice != 3); return 0; } |
Explanation:
- Classes:
MusicTrack
: Represents a music track with a title. It has a constructor to set the title and a method to retrieve the title.MusicPlayer
: Manages a playlist ofMusicTrack
objects. It can add tracks, play a specific track, and list all tracks in the playlist.
- Methods:
addTrack
: Adds aMusicTrack
to the playlist.playTrack
: Simulates playing a track by printing its title. It performs boundary checking to ensure the index is valid.listTracks
: Displays all the tracks in the playlist with their index.
- Main Function:
- Creates a
MusicPlayer
instance. - Adds a few sample tracks to the playlist.
- Provides a menu for the user to interact with the music player:
- Option 1: Lists all the tracks in the playlist.
- Option 2: Prompts the user to enter a track number and plays that track.
- Option 3: Exits the program.
- Creates a