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.
时间: 2023-07-26 10:03:32 浏览: 113
1) Inheritance:
```c++
#include <iostream>
#include <string>
class Animal {
protected:
std::string name;
public:
Animal(std::string n) : name(n) {}
void eat() {
std::cout << name << " is eating\n";
}
};
class Cat : public Animal {
public:
Cat(std::string n) : Animal(n) {}
void catchMouse() {
std::cout << name << " is catching a mouse\n";
}
};
class Dog : public Animal {
public:
Dog(std::string n) : Animal(n) {}
void bark() {
std::cout << name << " is barking\n";
}
};
int main() {
Cat cat("Kitty");
cat.eat();
cat.catchMouse();
Dog dog("Buddy");
dog.eat();
dog.bark();
return 0;
}
```
Output:
```
Kitty is eating
Kitty is catching a mouse
Buddy is eating
Buddy is barking
```
2) Polymorphism:
```c++
#include <iostream>
#include <string>
class Animal {
protected:
std::string name;
public:
Animal(std::string n) : name(n) {}
void eat() {
std::cout << name << " is eating\n";
}
virtual void speak() {}
};
class Cat : public Animal {
public:
Cat(std::string n) : Animal(n) {}
void catchMouse() {
std::cout << name << " is catching a mouse\n";
}
void speak() override {
std::cout << "Meow Meow Meow\n";
}
};
class Dog : public Animal {
public:
Dog(std::string n) : Animal(n) {}
void bark() {
std::cout << name << " is barking\n";
}
void speak() override {
std::cout << "Wow Woof Woof\n";
}
};
int main() {
Animal* ptr;
Cat cat("Kitty");
Dog dog("Buddy");
ptr = &cat;
ptr->speak();
ptr = &dog;
ptr->speak();
return 0;
}
```
Output:
```
Meow Meow Meow
Wow Woof Woof
```
阅读全文