⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 list1510.cpp

📁 《21天学通C++》Teach Yourself C++ in 21 Days (Fourth Edition) 源代码
💻 CPP
字号:
//Listing 15.10 Pointers to member functions using virtual methods

#include <iostream>
using namespace std;

class Mammal
{
  public:
     Mammal():itsAge(1) {  }
     virtual ~Mammal() { }
     virtual void Speak() const = 0;
     virtual void Move() const = 0;
  protected:
     int itsAge;
};

class Dog : public Mammal
{
  public:
    void Speak()const { cout << "Woof!" << endl; }
    void Move() const { cout << "Walking to heel..." << endl; }
};


class Cat : public Mammal
{
  public:
    void Speak()const { cout << "Meow!" << endl; }
    void Move() const { cout << "slinking..." << endl; }
};


class Horse : public Mammal
{
  public:
    void Speak()const { cout << "Winnie!" << endl; }
    void Move() const { cout << "Galloping..." << endl; }
};


int main()
{
   void (Mammal::*pFunc)() const =0;
   Mammal* ptr =0;
   int Animal;
   int Method;
   bool fQuit = false;

   while (fQuit == false)
   {
      cout << "(0)Quit (1)dog (2)cat (3)horse: ";
      cin >> Animal;
      switch (Animal)
      {
        case 1:   ptr = new Dog; break;
        case 2:   ptr = new Cat; break;
        case 3:   ptr = new Horse; break;
        default:  fQuit = true; break;
      }
      if (fQuit == false)
      {
         cout << "(1)Speak  (2)Move: ";
         cin >> Method;
         switch (Method)
         {
           case 1:  pFunc = Mammal::Speak; break;
           default: pFunc = Mammal::Move; break;
         }

          (ptr->*pFunc)();
         delete ptr;
      }
   }
   return 0;
}

⌨️ 快捷键说明

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