Problem Description
定义哺乳动物类Mammal,再由此派生出狗类Dog,定义一个Dog类的对象
//你的程序将被嵌在这里 int main() { Dog d; d.setAge(4); d.setWeight(12); d.setColor("Black"); cout<<d.getAge()<<endl; cout<<d.getWeight()<<endl; cout<<d.getColor()<<endl; d.speak(); return 0; }Sample Output
Constructor in Mammal. Constructor in Dog. 4 12 Black Dog sound wang,wang,wang! Destructor in Dog. Destructor in Mammal.Hint
1、类Mammal有数据成员Age(年龄,int类型)、Weight(体重,double类型),和对应的set函数以及get函数。 2、Dog定义了新的数据成员Color(颜色,string类型)。 3、Mammal类和Dog类都有成员函数speak。解题代码
#include <iostream> #include <string> using namespace std; class Mammal{ int age; double weight; public: Mammal(){cout << "Constructor in Mammal.\n";} ~Mammal(){cout << "Destructor in Mammal.\n";} void setAge(int Age) {age = Age;} void setWeight(int Weight) {weight = Weight;} int getAge(){return age;} double getWeight(){return weight;} }; class Dog:public Mammal{ string color; public: Dog(){cout << "Constructor in Dog.\n";} ~Dog(){cout << "Destructor in Dog.\n";} void setColor(string Color){color = Color;} string getColor(){return color;} void speak(){cout << "Dog sound wang,wang,wang!\n";} };