Grupo
Programación Orientada a Objetos en C++
Ojetivo
1. Define una clase base llamada "Animal" con dos métodos: makeSound y move.
2. Implementa el método makeSound para generar un sonido genérico y el método move para generar un movimiento genérico.
3. Crea dos clases derivadas: "Dog" y "Cat", que heredan de la clase "Animal".
4. Sobrescribe los métodos makeSound y move en las clases Dog y Cat para reflejar su comportamiento específico.
5. En la función principal, crea instancias de Dog y Cat, e invoca los métodos makeSound y move para cada una.
Escribe una clase Animal con los métodos makeSound y move, y luego crea clases derivadas como Dog y Cat.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the standard input/output library
using namespace std;
// Define the base class 'Animal'
class Animal {
public:
// Method to make a sound (generic)
virtual void makeSound() {
cout << "The animal makes a sound." << endl;
}
// Method to move (generic)
virtual void move() {
cout << "The animal moves." << endl;
}
// Virtual destructor
virtual ~Animal() {}
};
// Define the derived class 'Dog' which inherits from 'Animal'
class Dog : public Animal {
public:
// Override makeSound method for Dog
void makeSound() override {
cout << "The dog barks." << endl;
}
// Override move method for Dog
void move() override {
cout << "The dog runs." << endl;
}
};
// Define the derived class 'Cat' which inherits from 'Animal'
class Cat : public Animal {
public:
// Override makeSound method for Cat
void makeSound() override {
cout << "The cat meows." << endl;
}
// Override move method for Cat
void move() override {
cout << "The cat walks gracefully." << endl;
}
};
int main() {
// Create a Dog object and call its methods
Dog myDog;
myDog.makeSound(); // Dog-specific sound
myDog.move(); // Dog-specific movement
// Create a Cat object and call its methods
Cat myCat;
myCat.makeSound(); // Cat-specific sound
myCat.move(); // Cat-specific movement
return 0; // Return 0 to indicate successful execution
}
Salida
The dog barks.
The dog runs.
The cat meows.
The cat walks gracefully.
Comparte este ejercicio C++