derivedobject.cpp

来自「《24学时精通c++》的光盘内容」· C++ 代码 · 共 56 行

CPP
56
字号
 //Listing 16.2 Using a derived object

 #include <iostream>

 

 enum BREED { YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };

 

 class Mammal

 {

 public:

     // constructors

     Mammal():itsAge(2), itsWeight(5){}

     ~Mammal(){}

 

     //accessors

     int GetAge()const { return itsAge; }

     void SetAge(int age) { itsAge = age; }

     int GetWeight() const { return itsWeight; }

     void SetWeight(int weight) { itsWeight = weight; }

 

     //Other methods

     void Speak()const { std::cout << "Mammal sound!\n"; }

     void Sleep()const { std::cout << "shhh. I'm sleeping.\n"; }

 

 

 protected:

     int itsAge;

     int itsWeight;

 };

 

 class Dog : public Mammal

 {

 public:

     // Constructors

     Dog():itsBreed(YORKIE){}

     ~Dog(){}

 

     // Accessors

     BREED GetBreed() const { return itsBreed; }

     void SetBreed(BREED breed) { itsBreed = breed; }

 

     // Other methods

     void WagTail() { std::cout << "Tail wagging...\n"; }

     void BegForFood() { std::cout << "Begging for food...\n"; }

 

 private:

     BREED itsBreed;

 };

 

 int main()

 {

     Dog fido;

     fido.Speak();

     fido.WagTail();

     std::cout << "Fido is " << fido.GetAge() << " years old\n";

     return 0;

 }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?