• C++中用成员函数指针模拟多态


    1.成员函数指针的用法

     1 #include <iostream>
     2 using namespace std;
     3 class base
     4 {
     5 public:
     6    int test(int lhs,int rhs)
     7     {
     8         cout<<"base test"<<endl;
     9         return 1;
    10     }
    11 };
    12 class derived:public base
    13 {
    14 public:
    15     int test(int lhs,int rhs)
    16     {
    17         cout<<"derived test"<<endl;
    18         return 2;
    19     }
    20 };
    21 int main()
    22 {
    23     base *p;
    24     derived d;
    25     int (base::*baseFunction)(int,int);
    26     int (derived::*derivedFunction)(int,int);
    27     //基类指针指向子类对象+基类成员函数指针调用基类成员函数
    28     p=&d;
    29     baseFunction=&base::test;
    30     (p->*baseFunction)(1,2);//相当于d.base::test(int,int);
    31     //基类指针指向子类对象+基类成员函数指针调用子类成员函数
    32     p=&d;
    33     baseFunction=(int (base::*)(int,int))&derived::test;
    34     (p->*baseFunction)(1,2);//相当于d.test(int,int);
    35     return 0;
    36 }

    输出

    base test

    derived test

    2.成员函数指针模拟多态

     1 #include <iostream>
     2 using namespace std;
     3 class base
     4 {
     5 public:
     6     base()
     7     {
     8         virtualFunctionPointer=&base::test;
     9     }
    10     ~base()
    11     {
    12         
    13     }
    14     int (base::*virtualFunctionPointer)();
    15 
    16     int test()
    17     {
    18         //判断是否为基类实例,防止无限递归
    19         if(virtualFunctionPointer==&base::test)
    20         {
    21             cout<<"base"<<endl;
    22             return 1;
    23         }
    24         //子类对象通过基类指针调用test,多态
    25         else
    26            return (this->*virtualFunctionPointer)();
    27       
    28     }
    29 
    30 };
    31 class derived:public base
    32 {
    33 public:
    34   
    35     derived()
    36     {
    37         virtualFunctionPointer=(int (base::*)())&derived::test;
    38     }
    39     ~derived()
    40     {
    41         
    42     }
    43     int test()
    44     {
    45         cout<<"derived"<<endl;
    46         return 2;
    47     }
    48 
    49 };
    50 int main()
    51 {
    52     derived d;
    53     base *p=&d;
    54     cout<<p->test()<<endl;
    55     base b;
    56     p=&b;
    57     cout<<p->test()<<endl;
    58 
    59     return 0;
    60 }

     输出:

    derived

    2

    base

    1

  • 相关阅读:
    The server must be started under an unprivileged user ID to prevent
    it starts (“forks”) a new process for each connection.
    kong
    flume采集微信小程序数据
    bc
    LINUX上一个命令计算PI
    parameters arguments 形式参数 实际参数
    极限编程 简单设计
    Communicating sequential processes CSP 通信顺序进程 CSP writing to a file by name (process, Erlang) vs. writing to a file descriptor (channel, Go)
    hcitool
  • 原文地址:https://www.cnblogs.com/kyokuhuang/p/4392333.html
Copyright © 2020-2023  润新知