现有动物类Animal,包含名称name和年龄age数据成员,返回年龄GetAge、显示信息Showhe。由动物类派生出羊类Sheep和驼类Camel,前者增加重量、后者增加品种两个数据成员,都有显示信息的函数。羊驼类Alpace由羊类Sheep和驼类Camel公派生而来,定义各个类并在主函数内定义对象测试相关功能。
时间: 2024-02-13 14:03:20 浏览: 43
写一个类,名为Animal,该类有两个私有属性,name(代表动物的名字),和legs(代表动物的腿的条数);
好的,我明白了。以下是对应的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
// 定义动物类Animal
class Animal {
protected:
string name; // 名称
int age; // 年龄
public:
Animal(string name_, int age_) : name(name_), age(age_) {}
int GetAge() { return age; }
void Showhe() { cout << "Name: " << name << ", Age: " << age << endl; }
};
// 定义羊类Sheep
class Sheep : public Animal {
private:
float weight; // 重量
public:
Sheep(string name_, int age_, float weight_) : Animal(name_, age_), weight(weight_) {}
void Showhe() { cout << "Name: " << name << ", Age: " << age << ", Weight: " << weight << endl; }
};
// 定义驼类Camel
class Camel : public Animal {
private:
string breed; // 品种
public:
Camel(string name_, int age_, string breed_) : Animal(name_, age_), breed(breed_) {}
void Showhe() { cout << "Name: " << name << ", Age: " << age << ", Breed: " << breed << endl; }
};
// 定义羊驼类Alpace
class Alpace : public Sheep, public Camel {
public:
Alpace(string name_, int age_, float weight_, string breed_) : Sheep(name_, age_, weight_), Camel(name_, age_, breed_), Animal(name_, age_) {}
void Showhe() { cout << "Name: " << name << ", Age: " << age << ", Weight: " << Sheep::weight << ", Breed: " << Camel::breed << endl; }
};
int main() {
Sheep sheep("Mary", 2, 35.5);
Camel camel("Lucy", 5, "Bactrian");
Alpace alpace("Tom", 3, 40.2, "Hybrid");
sheep.Showhe();
camel.Showhe();
alpace.Showhe();
return 0;
}
```
这里我们通过继承实现了羊类Sheep,驼类Camel和羊驼类Alpace,并且它们都可以输出自己的信息。在主函数中,我们定义了三个对象分别测试它们的功能。
阅读全文