一次c++关于派生类的例子
这是一个c++的派生类与基类的例子,写得不精。
题目:动物类Mammal私有成员数据包含年龄age和体重weight,均是int类型。Mammal类包含成员函数show。
狗类Dog由Mammal类公有派生而来,包含私有成员数据颜色(int color)。Dog类包含成员函数show。 每组测试数据1行,每行包括3个整数,分别表示年龄、体重和颜色(取值0(黑色)1(白色)2(金色)3(黑白花色))。
#include<iostream>
using namespace std;
class Mammal{
private:
int age,weight;
public:
Mammal(void);
Mammal(int New_age,int New_weight);
Mammal(const Mammal &m);
~Mammal(void);
void show(void);
int Get_age(void);
int Get_weight(void);
};
class Dog:public Mammal{
private:
int color;
public:
Dog(void);
Dog(int New_age,int New_weight,int New_color);
Dog(const Mammal m,int New_color);
Dog(int New_color);
Dog(const Mammal m);
~Dog(void);
void show(void);
};
//************************************
Mammal::Mammal(void)
{
age=0;
weight=0;
cout<<"Function #1 is called!"<<endl;
}
Mammal::Mammal(int New_age,int New_weight):age(New_age),weight(New_weight)
{
cout<<"Function #2 is called!"<<endl;
}
Mammal::Mammal(const Mammal &m):age(m.age),weight(m.weight){}
Mammal::~Mammal(void){}
void Mammal::show(void)
{
cout<<age<<"岁/"<<weight<<"kg"<<endl;
cout<<"Function #3 is called!"<<endl;
}
int Mammal::Get_age(void)
{
return age;
}
int Mammal::Get_weight(void)
{
return weight;
}
//**********************************
Dog::Dog(void):Mammal()
{
color=0;
cout<<"Function #4 is called!"<<endl;
}
Dog::Dog(int New_age,int New_weight,int New_color):Mammal(New_age,New_weight),color(New_color)
{
cout<<"Function #5 is called!"<<endl;
}
Dog::Dog(Mammal m,int New_color):Mammal(m),color(New_color)
{
cout<<"Function #6 is called!"<<endl;
}
Dog::Dog(int New_color):color(New_color)
{
cout<<"Function #7 is called!"<<endl;
}
Dog::Dog(Mammal m):Mammal(m)
{
color=0;
cout<<"Function #8 is called!"<<endl;
}
Dog::~Dog(void){}
void Dog::show(void)
{
char COLOR;
if(color==0)
cout<<"黑色/";
else if(color==1)
cout<<"白色/";
else if(color==2)
cout<<"金色/";
else
cout<<"黑白花色/";
Mammal::show();
cout<<"Function #9 is called!"<<endl;
}
//***********************************
int main(void)
{
int age,weight,color,cas=0;
Mammal m0;
Dog d0;
cout<<"Mammal0:"; m0.show();
cout<<"Dog0:"; d0.show();
while(cin>>age>>weight>>color)
{
cas++;
cout<<"Case #"<<cas<<":"<<endl;
Mammal m1(age,weight);
Dog d1(age,weight,color);
Dog d2(m1,color);
Dog d3(color);
Dog d4(m1);
cout<<"Mammal1:"; m1.show();
cout<<"Dog1:"; d1.show();
cout<<"Dog2:"; d2.show();
cout<<"Dog3:"; d3.show();
cout<<"Dog4:"; d4.show();
}
return 0;
}
第一次尝试,可能有些地方写得不好,还望别作为标准。