Grupo
Programación Orientada a Objetos en C++
Ojetivo
1. Define una clase llamada Book con atributos privados: título, autor y precio.
2. Crea un constructor que inicialice estos atributos.
3. Implementa un método llamado displayInfo que imprima el título, el autor y el precio del libro.
4. En la función principal, crea una instancia de la clase Book y llama al método displayInfo para mostrar la información almacenada.
Crea una clase Book que incluya atributos como título, autor y precio.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include input-output stream for console interaction
#include <string> // Include string library to use string data type
using namespace std;
// Define the Book class
class Book {
private:
string title; // Variable to store the title of the book
string author; // Variable to store the author's name
double price; // Variable to store the price of the book
public:
// Constructor to initialize all attributes of the Book
Book(string t, string a, double p) {
title = t;
author = a;
price = p;
}
// Method to display the book's information
void displayInfo() {
cout << "Book Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Price: $" << price << endl;
}
};
int main() {
// Create an object of the Book class with sample data
Book myBook("The Great Gatsby", "F. Scott Fitzgerald", 12.99);
// Display the book's details
myBook.displayInfo();
return 0; // End of the program
}
Salida
Book Title: The Great Gatsby
Author: F. Scott Fitzgerald
Price: $12.99
Comparte este ejercicio C++