用c++编写1、已知猫和狗的基本信息如下,请设计猫狗类,并在主函数中通过对象使用它们特有的方法 已知猫类和狗类: 属性:毛的颜色,腿的个数行为:吃饭 (1)猫特有行为:抓老鼠catchMouse (2)狗特有行为:看家lookHome
时间: 2024-02-03 19:14:36 浏览: 28
以下是使用C++编写的猫和狗类:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 定义Animal类
class Animal {
protected:
string color; // 毛的颜色
int leg_num; // 腿的个数
public:
Animal(string c, int n) : color(c), leg_num(n) {}
void eat() {
cout << "Animal is eating." << endl;
}
};
// 定义Cat类
class Cat : public Animal {
public:
Cat(string c, int n) : Animal(c, n) {}
void catchMouse() {
cout << "Cat is catching mouse." << endl;
}
};
// 定义Dog类
class Dog : public Animal {
public:
Dog(string c, int n) : Animal(c, n) {}
void lookHome() {
cout << "Dog is looking after the house." << endl;
}
};
int main() {
Cat cat("white", 4);
Dog dog("black", 4);
cat.eat(); // Animal is eating.
cat.catchMouse(); // Cat is catching mouse.
dog.eat(); // Animal is eating.
dog.lookHome(); // Dog is looking after the house.
return 0;
}
```
在这个例子中,我们定义了一个基类 `Animal`,它有两个属性 `color` 和 `leg_num`,以及一个方法 `eat()`。然后我们分别继承 `Animal` 类,定义了 `Cat` 类和 `Dog` 类,并在它们的类中定义了特有的方法 `catchMouse()` 和 `lookHome()`。
在主函数中,我们创建了一个 `Cat` 对象和一个 `Dog` 对象,调用它们特有的方法。同时,我们也可以调用它们从基类继承而来的 `eat()` 方法。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)