[C++基础]用C实现C++特性

函数指针

Posted by JinFei on March 9, 2020

函数指针 封装

//函数指针
// void (*pf)(int) 名为pf,指向一个返回值为空,形参列表为int的函数指针
#include <stdio.h>
typedef struct Astruct
{
    int _a;   //成员变量
    void(*pf1)();  //成员函数指针
    int (*pf2)();
}*Astr;
int  print1()
{
    return 0;
}
int  print2()
{
    return 1;
}
void initastr(Astr str,int a)
{
    str->_a = a;
    str->pf1 = print1;
    str->pf2 = print2;
    printf("%d\n", *(str->pf1));
    printf("%d\n", *(str->pf2));

}
int main()
{
    Astr aa = (Astr) malloc(sizeof(int)*4);
    initastr( aa, 3);
    printf("%d\n", aa->_a);
    return 0;
}

继承

typedef struct A
{
    int _a;
}A;
typedef struct B
{
    A a;
    int _b;
}B;

函数指针 多态

#include <stdio.h>

struct A
{
    int _a;
    void(*print) (void *p);//函数指针

};
 struct B
{
     struct A Pa;   //包含一个A类的对象 Pa
};

void printpa(void * p)
{

    if (p == NULL)
        return;
    printf("call  A\n");
}
void printpb(void * p)
{

    if (p == NULL)
        return;
    printf("call  B\n");
}
void print_F(void* p)
{
    if (p == NULL)
        return;
    struct A* pa = (struct A*)p;
    pa->print(p);
}
int main()
{
    struct A a;
    struct B b;
    a.print = printpa;  //A 中的函数指针指向函数
    b.Pa.print = printpb;//B通过A的对象的函数指针指向的函数
    print_F(&a);
    print_F(&b);
    return 0;
}

实现多态

#include <stdio.h>

typedef void (*Fun)();  // 定义一个函数指针
struct A{
    Fun fun;
    int a;
};

struct B{
    A a;
    int b;
};

void fa(){
    printf("A fun called ...\n");
}

void fb(){
    printf("B fun called ...\n");
}

int main(){
    A a;
    a.fun = fa;
    B b;
    b.a.fun = fb;
    
    A* p = &a;
    p -> fun();
    // p = (A*)&b;  // 需要强转
    // p -> fun();
    return 0;
}