• 拳击游戏(虚函数应用)


    代码示例

     1 #include <iostream>
     2 using namespace std;
     3 class poser
     4 {
     5 public:
     6     virtual void beat()const{ cout << "一般选手的力量为260磅
    "; }//定义为虚函数
     7 protected:
     8     int age;
     9 };
    10 class Ali :public poser
    11 {
    12 public:
    13     void beat()const{ cout << "阿里一拳的力量为420磅
    "; }//由虚函数的类派生而来,子类beat()也是虚函数,virtual可加可不加
    14 };
    15 class Levis :public poser
    16 {
    17 public:
    18     void beat()const{ cout << "刘易斯一拳的力量为480磅
    "; }
    19 };
    20 class Tyson :public poser
    21 {
    22 public:
    23     void beat()const{ cout << "泰森一拳的力量为500磅
    "; }
    24 };
    25 class Holy :public poser
    26 {
    27 public:
    28     void beat()const{ cout << "霍利菲尔德一拳的力量为350磅
    "; }
    29 };
    30 int main()
    31 {
    32     poser *p[5];                            //定义一个含有5个指针的指针数组
    33     poser *p1;                                //定义临时指针变量
    34     int choice, i;
    35     for (i = 0; i<5; i++)
    36     {
    37         cout << "*********(1)阿里(2)刘易斯(3)泰森(4)霍利菲尔德**********";
    38         cin >> choice;                        //用户输入的临时变量
    39         switch (choice)
    40         {
    41         case 1:p1 = new Ali;
    42             break;
    43         case 2:p1 = new Levis;
    44             break;
    45         case 3:p1 = new Tyson;
    46             break;
    47         case 4:p1 = new Holy;
    48             break;
    49         default:p1 = new poser;                //当输入为其他情况时
    50             break;
    51         }
    52         p[i] = p1;                            //将临时变量中的对象的地址赋值给指针数组,共执行5次
    53         p[i]->beat();                        //指针数组自动调用对应对象中的beat()函数
    54     }
    55 }

    结果演示

  • 相关阅读:
    lambda表达式
    解读Raft(一 算法基础)
    译《Time, Clocks, and the Ordering of Events in a Distributed System》
    如何在MQ中实现支持任意延迟的消息?
    读Kafka Consumer源码
    2017上海QCon之旅总结(下)
    2017上海QCon之旅总结(中)
    2017上海QCon之旅总结(上)
    什么是WAL?
    Push or Pull?
  • 原文地址:https://www.cnblogs.com/table/p/4729281.html
Copyright © 2020-2023  润新知