Grupo
Programación Orientada a Objetos en C++
Ojetivo
1. Defina una clase llamada Vehículo con un atributo booleano para controlar si el motor está encendido.
2. Implemente un método para arrancar el vehículo. Si ya está arrancado, muestre un mensaje.
3. Implemente un método para simular el frenado mostrando un mensaje.
4. Implemente un método para simular la conducción. El vehículo debe arrancarse primero para poder conducir.
5. En la función principal, cree un objeto Vehículo e invoque sus métodos para demostrar el comportamiento.
Implemente una clase Vehículo con métodos para arrancar, frenar y conducir.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include input-output stream library
using namespace std;
// Define the Vehicle class
class Vehicle {
private:
bool engineOn; // Boolean to track if the engine is started
public:
// Constructor initializes the vehicle with the engine off
Vehicle() {
engineOn = false;
}
// Method to start the vehicle
void start() {
if (engineOn) {
// If the engine is already on, notify the user
cout << "The vehicle is already started." << endl;
} else {
// Start the engine
engineOn = true;
cout << "Vehicle started successfully." << endl;
}
}
// Method to brake the vehicle
void brake() {
// Display a message to simulate braking
cout << "Vehicle is braking." << endl;
}
// Method to drive the vehicle
void drive() {
if (engineOn) {
// If the engine is on, simulate driving
cout << "Vehicle is driving." << endl;
} else {
// If the engine is off, notify the user
cout << "Cannot drive. Please start the vehicle first." << endl;
}
}
};
int main() {
// Create an object of the Vehicle class
Vehicle car;
// Attempt to drive before starting
car.drive();
// Start the vehicle
car.start();
// Attempt to start the vehicle again
car.start();
// Drive the vehicle
car.drive();
// Apply the brakes
car.brake();
return 0; // End the program
}
Salida
Cannot drive. Please start the vehicle first.
Vehicle started successfully.
The vehicle is already started.
Vehicle is driving.
Vehicle is braking.
Comparte este ejercicio C++