1) Inheritance:Suppose there is a base class `Animal` that has a `name` property and an `eat()` method. Now there are two derived classes `Cat` and `Dog`, both of which inherit from the `Animal` class. The `Cat` class has a `catchMouse()` method and the `Dog` class has a `bark()` method. Write the main() function that does the following: create a `Cat` object and a `Dog` object; assign values to their `name` properties, respectively; call the `eat()` and `catchMouse()` methods of the `Cat` object; call the `eat()` and `bark()` methods of the `Dog` object. 2)Polymorphism: Based on 1), add a virtual function speak() in the base class Animal to represent the behavior of animals making sounds. The two derived classes Dog and Cat implement the speak() function respectively, and output "Wow Woof Woof" and "Meow Meow Meow" respectively. Please define a pointer to the Animal object in the main function, let it point to the Dog object and the Cat object, and call their speak() function. Submit your completed program as a single C++ source file.
时间: 2023-07-26 17:03:32 浏览: 173
1) Here's the code for the inheritance example:
```c++
#include <iostream>
#include <string>
class Animal {
public:
std::string name;
void eat() {
std::cout << name << " is eating." << std::endl;
}
};
class Cat : public Animal {
public:
void catchMouse() {
std::cout << name << " is catching a mouse." << std::endl;
}
};
class Dog : public Animal {
public:
void bark() {
std::cout << name << " is barking." << std::endl;
}
};
int main() {
Cat cat;
cat.name = "Tom";
cat.eat();
cat.catchMouse();
Dog dog;
dog.name = "Fido";
dog.eat();
dog.bark();
return 0;
}
```
2) Here's the updated code for the polymorphism example:
```c++
#include <iostream>
#include <string>
class Animal {
public:
std::string name;
void eat() {
std::cout << name << " is eating." << std::endl;
}
virtual void speak() {
std::cout << name << " is making a sound." << std::endl;
}
};
class Cat : public Animal {
public:
void catchMouse() {
std::cout << name << " is catching a mouse." << std::endl;
}
void speak() override {
std::cout << "Meow Meow Meow" << std::endl;
}
};
class Dog : public Animal {
public:
void bark() {
std::cout << name << " is barking." << std::endl;
}
void speak() override {
std::cout << "Wow Woof Woof" << std::endl;
}
};
int main() {
Animal* animalPtr;
Cat cat;
cat.name = "Tom";
animalPtr = &cat;
animalPtr->speak();
Dog dog;
dog.name = "Fido";
animalPtr = &dog;
animalPtr->speak();
return 0;
}
```
Note that the `speak()` function is marked as `virtual` in the base class `Animal`, which means that it can be overridden by derived classes. In the `Cat` and `Dog` classes, we override the `speak()` function to output the appropriate sound for each animal. In the `main()` function, we define a pointer to an `Animal` object, and we use it to point to both a `Cat` object and a `Dog` object. We then call the `speak()` function through the pointer, and each animal outputs its own sound.
阅读全文