1、实现Mammal类的方法
2、由Mammal类派生出Dog类,在Dog类中增加itsColor成员(COLOR类型)
3、Dog类中增加以下方法:
constructors: Dog()、Dog(int age)、Dog(int age, int weight)、Dog(int age, COLOR color)、 Dog(int age, int weight, COLOR color)、~Dog()
accessors: GetColor()、SetColor()
Other methods: WagTail()、BegForFood() ,并实现以上这些方法 。
提示:类似Speak()、WagTail()这些动作,函数体可以是输出一句话。比如:Mammal is spaeking... , The Dog is Wagging its tail...
4、补充主函数的问号部分,并运行程序,检查输出是否合理。
1 #include<iostream> 2 using namespace std; 3 enum COLOR{ WHITE, RED, BROWN, BLACK, KHAKI }; 4 class Mammal 5 { 6 public: 7 //constructors 8 Mammal(); 9 Mammal(int age); 10 ~Mammal(); 11 12 //accessors 13 int GetAge() const; 14 void SetAge(int); 15 int GetWeight() const; 16 void SetWeight(int); 17 18 //Other methods 19 void Speak() const; 20 void Sleep() const; 21 protected: 22 int itsAge; 23 int itsWeight; 24 }; 25 Mammal::Mammal(){}//定义构造函数 26 Mammal::Mammal(int age):itsAge(age){} 27 Mammal::~Mammal(){} 28 int Mammal::GetAge() const//用于获取itsAge 29 { 30 return itsAge; 31 } 32 void Mammal::SetAge(int age)//用于设置itsAge 33 { 34 itsAge=age; 35 } 36 int Mammal::GetWeight() const//用于获取itsWeight 37 { 38 return itsWeight; 39 } 40 void Mammal::SetWeight(int weight)//用于设置itsWeight 41 { 42 itsWeight=weight; 43 } 44 void Mammal::Speak() const//成员函数 45 { 46 cout<<"Mammal is speaking..."<<endl; 47 } 48 void Mammal::Sleep() const//成员函数 49 { 50 cout<<"Mammal is sleeping..."<<endl; 51 } 52 53 class Dog:public Mammal//定义Dog类,继承Mammal类 54 { 55 private: 56 COLOR itsColor;//设置颜色为私有属性,类型为枚举COLOR类型 57 public: 58 Dog(); 59 Dog(int age); 60 Dog(int age,int weight); 61 Dog(int age,COLOR color); 62 Dog(int age,int weight,COLOR color); 63 ~Dog(); 64 COLOR GetColor(); 65 void SetColor(COLOR color); 66 void WagTail(); 67 void BegForFood(); 68 }; 69 Dog::Dog(){}//定义构造函数 70 Dog::Dog(int age):Mammal(age){}//调用基类的构造函数 71 Dog::Dog(int age,int weight):Mammal(age) 72 { 73 this->SetWeight(weight); 74 } 75 Dog::Dog(int age,COLOR color):Mammal(age) 76 { 77 this->itsColor=color; 78 } 79 Dog::Dog(int age,int weight,COLOR color):Mammal(age) 80 { 81 this->SetWeight(weight); 82 this->itsColor=color; 83 } 84 Dog::~Dog(){}//定义析构函数 85 COLOR Dog::GetColor()//获取对象的itsColor值 86 { 87 return itsColor; 88 } 89 void Dog::SetColor(COLOR color)//设置对象的itsCokor值 90 { 91 itsColor=color; 92 } 93 void Dog::WagTail()//定义成员函数 94 { 95 cout<<"The dog is wagging its tail..."<<endl; 96 } 97 void Dog::BegForFood()//定义成员函数 98 { 99 cout<<"The dog is begging its food..."<<endl; 100 } 101 int main() 102 { 103 Dog Fido; 104 Dog Rover(5); 105 Dog Buster(6, 8); 106 Dog Yorkie(3, RED); 107 Dog Dobbie(4, 20, KHAKI); 108 Fido.Speak(); 109 Rover.WagTail(); 110 cout<<"Yorkie is "<<Yorkie.GetAge()<<" years old."<<endl; 111 cout<<"Dobbie weighs "<<Dobbie.GetWeight()<<" pounds."<<endl; 112 return 0; 113 }
构造函数和析构函数只声明不定义会报错