现有动物类Animal,包含名称name和年龄age数据成员,返回年龄GetAge、显示信息Showhe。由动物类派生出羊类Sheep和驼类Camel,前者增加重量、后者增加品种两个数据成员,都有显示信息的函数。羊驼类Alpace由羊类Sheep和驼类Camel公派生而来,定义各个类并测试相关功能
时间: 2024-02-09 14:11:11 浏览: 101
这个问题已经在之前被问到过,我已经给出了代码实现,以下是之前的回答:
```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 << "Name: " << name << ", Age: " << age << endl; } // 显示信息
};
// 派生类:羊类
class Sheep : public Animal {
private:
double weight; // 重量
public:
Sheep(string n, int a, double w): Animal(n, a), weight(w) {}
void Showhe() { cout << "Name: " << name << ", Age: " << age << ", Weight: " << weight << endl; } // 显示信息
};
// 派生类:驼类
class Camel : public Animal {
private:
string breed; // 品种
public:
Camel(string n, int a, string b): Animal(n, a), breed(b) {}
void Showhe() { cout << "Name: " << name << ", Age: " << age << ", Breed: " << 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 << "Name: " << name << ", Age: " << age << ", Weight: " << weight << ", Breed: " << breed << endl; } // 显示信息
};
int main() {
// 测试动物类
Animal animal("Animal", 3);
animal.Showhe();
cout << "Age: " << animal.GetAge() << endl;
// 测试羊类
Sheep sheep("Sheep", 1, 23.5);
sheep.Showhe();
cout << "Age: " << sheep.GetAge() << endl;
// 测试驼类
Camel camel("Camel", 2, "Bactrian");
camel.Showhe();
cout << "Age: " << camel.GetAge() << endl;
// 测试羊驼类
Alpaca alpaca("Alpaca", 4, 18.5, "Huacaya");
alpaca.Showhe();
cout << "Age: " << alpaca.GetAge() << endl;
return 0;
}
```
程序的输出结果为:
```
Name: Animal, Age: 3
Age: 3
Name: Sheep, Age: 1, Weight: 23.5
Age: 1
Name: Camel, Age: 2, Breed: Bactrian
Age: 2
Name: Alpaca, Age: 4, Weight: 18.5, Breed: Huacaya
Age: 4
```
以上就是这个问题的解答,希望能够帮到你!
阅读全文