Problem Description
哺乳动物类Mammal,有年龄age、重量weight、颜色color数据成员。
狗类Dog由哺乳动物类Mammal派生。添加必要的函数成员,完成以下程序。
//你的程序将被嵌在这里
int main()
{
Dog d1(3,8,“红色”);
d1.display();
Dog d2;
d2 = d1;
d2.display();
Dog d3 = d1;
d3.display();
return 0;
}
Sample Output
调用构造函数Mammal(int a,int w,string c)
调用构造函数Dog(int a, int w, string c)
狗的年龄:3
狗的重量:8
狗的颜色:红色
调用构造函数Mammal()
调用构造函数Dog()
狗的年龄:3
狗的重量:8
狗的颜色:红色
调用构造函数Mammal(int a,int w,string c)
调用拷贝构造函数
狗的年龄:3
狗的重量:8
狗的颜色:红色
调用析构函数~Dog()
调用析构函数~Mammal()
调用析构函数~Dog()
调用析构函数~Mammal()
调用析构函数~Dog()
调用析构函数~Mammal()
#include <iostream>
using namespace std;
#include <string>
class Mammal
{
public:
int age;
int weight;
string color;
Mammal()
{
cout << "调用构造函数Mammal()" << endl;
}
Mammal(int a, int b, string c)
{
age = a;
weight = b;
color = c;
cout << "调用构造函数Mammal(int a,int w,string c)" << endl;
}
Mammal(const Mammal& p)
{
age = p.age;
weight = p.weight;
color = p.color;
cout << "调用构造函数Mammal(int a,int w,string c)" << endl;
cout << "调用拷贝构造函数" << endl;
}
~Mammal()
{
cout << "调用析构函数~Mammal()" << endl;
}
};
class Dog:public Mammal
{
public:
Dog()
{
cout << "调用构造函数Dog()" << endl;
}
Dog(int a, int b, string c):Mammal(a,b,c)
{
age = a;
weight = b;
color = c;
cout << "调用构造函数Dog(int a, int w, string c)" << endl;
}
void display()
{
cout << "狗的年龄:" << age << endl;
cout << "狗的重量:" << weight << endl;
cout << "狗的颜色:" << color << endl;
}
~Dog()
{
cout << "调用析构函数~Dog()" << endl;
}
};
int main()
{
Dog d1(3, 8, "红色");
d1.display();
Dog d2;
d2 = d1;
d2.display();
Dog d3 = d1;
d3.display();
return 0;
}