定义一个动物类Animal,成员变量包括:int型的m_weight体重,成员函数包括构造函数Animal(int )和成员函数GetWeigh().
由Animal类派生出马类Horse,添加构造函数和成员函数Run(){cout<<"I can run.";}
由Animal类派生出鸟类Bird,添加构造函数和成员函数Fly(){cout<<"I can fly.";}
由Horse类和Bird类共同派生出天马类Pegasus,添加构造函数和输出函数(使用基类继承而来的成员函数)。
设计主函数,建立天马类对象,并输出。
#include<iostream>
using namespace std;
class Animal
{ protected:
int m_weight;
public:
Animal(){};
void Getweight(){cin>>m_weight;}
};
class Horse:virtual public Animal
{
public:
Horse(){}
void Run(){cout<<"I can run."<<endl;}
};
class Bird:virtual public Animal
{ public:
Bird(){}
void Fly(){cout<<"I can fly."<<endl;}
};
class Pegasus:public Horse,public Bird
{
public:
Pegasus(){}
void show()
{ cout<<"I am a Pegasus. "<<endl;
cout<<"My weight is "<<m_weight<<"kg."<<endl;
}
};
int main()
{
Pegasus p1;
p1.Getweight();
p1.show();
p1.Run();
p1.Fly();
return 0;
}