现有动物类Animal,包含名称name和年龄age数据成员,返回年龄GetAge、显示信息Showhe。由动物类派生出羊类Sheep和驼类Camel,前者增加重量、后者增加品种两个数据成员,都有显示信息的函数。羊驼类Alpace由羊类Sheep和驼类Camel公派生而来,定义各个类并测试相关功能。
时间: 2024-02-11 16:04:00 浏览: 32
好的,我理解了你的问题。下面是代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class Animal {
protected:
string name;
int age;
public:
Animal(string n, int a) : name(n), age(a) {}
int GetAge() { return age; }
void Showhe() { cout << "I'm an animal. My name is " << name << " and I'm " << age << " years old." << endl; }
};
class Sheep : public Animal {
private:
double weight;
public:
Sheep(string n, int a, double w) : Animal(n, a), weight(w) {}
void Showhe() { cout << "I'm a sheep. My name is " << name << " and I'm " << age << " years old. My weight is " << weight << " kg." << endl; }
};
class Camel : public Animal {
private:
string breed;
public:
Camel(string n, int a, string b) : Animal(n, a), breed(b) {}
void Showhe() { cout << "I'm a camel. My name is " << name << " and I'm " << age << " years old. My breed is " << breed << "." << endl; }
};
class Alpaca : public Sheep, public Camel {
public:
Alpaca(string n, int a, double w, string b) : Sheep(n, a, w), Camel(n, a, b), Animal(n, a) {}
void Showhe() { cout << "I'm an alpaca. My name is " << name << ", I'm " << age << " years old, my weight is " << Sheep::weight << " kg, and my breed is " << Camel::breed << "." << endl; }
};
int main() {
Sheep s("Dolly", 2, 20.5);
Camel c("Humphrey", 4, "Bactrian");
Alpaca a("Paco", 3, 25.0, "Huacaya");
s.Showhe();
c.Showhe();
a.Showhe();
return 0;
}
```
在上面的代码中,我们定义了一个基类 Animal,它包含了名称 name 和年龄 age 数据成员,还有获取年龄 GetAge 和显示信息 Showhe 的函数。然后我们派生出了羊类 Sheep 和驼类 Camel,它们分别增加了一个重量 weight 和品种 breed 的数据成员,并重载了显示信息的函数。最后,羊驼类 Alpaca 由羊类 Sheep 和驼类 Camel 公派生而来,它继承了它们的数据成员和函数,并增加了一个 Animal 基类的对象,以便访问 Animal 中的数据成员和函数。最后我们在 main 函数中测试了各个类的功能。