现有动物类Animal,包含名称name和年龄age数据成员,返回年龄GetAge、显示信息Showhe。由动物类派生出羊类Sheep和驼类Camel,前者增加重量、后者增加品种两个数据成员,都有显示信息的函数。羊驼类Alpace由羊类Sheep和驼类Camel公派生而来,定义各个类并测试相关功能。
时间: 2024-02-05 13:12:49 浏览: 28
以下是对应的代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
// 动物类Animal
class Animal {
protected:
string name; // 名称
int age; // 年龄
public:
Animal(string n, int a) : name(n), age(a) {} // 构造函数
int GetAge() { return age; } // 返回年龄
void Showhe() { // 显示信息
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
// 羊类Sheep
class Sheep : public Animal {
private:
double weight; // 重量
public:
Sheep(string n, int a, double w) : Animal(n, a), weight(w) {} // 构造函数
void Showhe() { // 显示信息
Animal::Showhe();
cout << "Weight: " << weight << endl;
}
};
// 驼类Camel
class Camel : public Animal {
private:
string breed; // 品种
public:
Camel(string n, int a, string b) : Animal(n, a), breed(b) {} // 构造函数
void Showhe() { // 显示信息
Animal::Showhe();
cout << "Breed: " << breed << endl;
}
};
// 羊驼类Alpaca
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() { // 显示信息
Animal::Showhe();
cout << "Weight: " << Sheep::weight << endl;
cout << "Breed: " << Camel::breed << endl;
}
};
int main() {
// 测试
Alpaca alpaca("Alpaca", 3, 56.2, "Huacaya");
alpaca.Showhe();
return 0;
}
```
输出结果:
```
Name: Alpaca
Age: 3
Weight: 56.2
Breed: Huacaya
```