zoukankan      html  css  js  c++  java
  • C语言多态与继承

    C语言多态与继承

    void *与函数指针、结构体是c语言能实现继承与多态的重要组成部分。

    void *:万能的指针

    int * 叫做指向整型的指针,而 char * 是指向字符型的指针等等。

    而 void *,不要按照通常的命名方式叫它做指向 void 类型的指针,它的正式的名字叫做:可以指向任意类型的指针。

    函数指针:指向函数的指针

    示例代码:

    #include <stdio.h>
    #include <stdlib.h>
     
    //虚函数表结构
    struct base_vtbl
    {
        void(*dance)(void *);
        void(*jump)(void *);
    };
     
    //基类
    struct base
    {
        /*virtual table*/
        struct base_vtbl *vptr;
    };
     
    void base_dance(void *this)
    {
        printf("base dance
    ");
    }
     
    void base_jump(void *this)
    {
        printf("base jump
    ");
    }
     
    /* global vtable for base */
    struct base_vtbl base_table =
    {
            base_dance,
            base_jump
    };
     
    //基类的构造函数
    struct base * new_base()
    {
        struct base *temp = (struct base *)malloc(sizeof(struct base));
        temp->vptr = &base_table;
        return temp;
    }
     
     
    //派生类
    struct derived1
    {
        struct base super;
        /*derived members */
        int high;
    };
     
    void derived1_dance(void * this)
    {
        /*implementation of derived1's dance function */
        printf("derived1 dance
    ");
    }
     
    void derived1_jump(void * this)
    {
        /*implementation of derived1's jump function */
        struct derived1* temp = (struct derived1 *)this;
        printf("derived1 jump:%d
    ", temp->high);
    }
     
    /*global vtable for derived1 */
    struct base_vtbl derived1_table =
    {
        (void(*)(void *))&derived1_dance,
        (void(*)(void *))&derived1_jump
    };
     
    //派生类的构造函数
    struct derived1 * new_derived1(int h)
    {
        struct derived1 * temp= (struct derived1 *)malloc(sizeof(struct derived1));
        temp->super.vptr = &derived1_table;
        temp->high = h;
        return temp;
    }
     
     
     
    int main(void)
    {
     
        struct base * bas = new_base();
        //这里调用的是基类的成员函数
        bas->vptr->dance((void *)bas);
        bas->vptr->jump((void *)bas);
     
     
        struct derived1 * child = new_derived1(100);
        //基类指针指向派生类
        bas  = (struct base *)child;
     
        //这里调用的其实是派生类的成员函数
        bas->vptr->dance((void *)bas);
        bas->vptr->jump((void *)bas);
        return 0;
    }
  • 相关阅读:
    兴趣与心态比较重要【转】
    网站发布到iis上,附加进程调试,打不到断点
    MVC时间格式化
    javascript数组扁平化处理
    Object.prototype.toString.call()
    获取浏览器大小
    HTTP状态码
    未能加载文件或程序集“Microsoft.ReportViewer.WebForms, Version=10.0.0.0
    javascript基础知识-1
    Html5上传图片的预览
  • 原文地址:https://www.cnblogs.com/-wenli/p/12613567.html
Copyright © 2011-2022 走看看