现有动物类Animal,包含名称name和年龄age数据成员,返回年龄GetAge、显示信息Showhe。由动物类派生出羊类Sheep和驼类Camel,前者增加重量、后者增加品种两个数据成员,都有显示信息的函数。羊驼类Alpace由羊类Sheep和驼类Camel公派生而来,定义各个类并测试相关功能。
时间: 2024-02-05 16:13:31 浏览: 80
动物数据集Animal Dataset
5星 · 资源好评率100%
以下是代码实现:
```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; }
virtual void ShowInfo() {}
};
class Sheep : public Animal {
private:
double weight;
public:
Sheep(string n, int a, double w) : Animal(n, a), weight(w) {}
void ShowInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Weight: " << weight << endl;
}
};
class Camel : public Animal {
private:
string breed;
public:
Camel(string n, int a, string b) : Animal(n, a), breed(b) {}
void ShowInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "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 ShowInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Weight: " << Sheep::weight << endl;
cout << "Breed: " << Camel::breed << endl;
}
};
int main() {
Sheep sheep("Dolly", 2, 30.5);
Camel camel("Sandy", 5, "Bactrian");
Alpaca alpaca("Paco", 1, 20.2, "Huacaya");
cout << "Sheep Info: " << endl;
sheep.ShowInfo();
cout << "Camel Info: " << endl;
camel.ShowInfo();
cout << "Alpaca Info: " << endl;
alpaca.ShowInfo();
return 0;
}
```
运行结果:
```
Sheep Info:
Name: Dolly
Age: 2
Weight: 30.5
Camel Info:
Name: Sandy
Age: 5
Breed: Bactrian
Alpaca Info:
Name: Paco
Age: 1
Weight: 20.2
Breed: Huacaya
```
阅读全文