【C++】C语言(结构体)简单模拟动态联编

首先:设计一个方法来输出方形和圆形的面积
1.设计一个函数指针
2.表示形状的结构体
3.表示圆形和方形的结构体
4.计算面积

typedef struct _ops
{
    float (*area)(void*);  //面积
}Ops;

//代表形状的结构体

typedef struct _Shape
{ 
    Ops ops;   //形状
}Shape;
typedef struct _Square
{
    Shape shape;  //保留形状
    float length;
}Square;
typedef struct Ciccle
{
    Shape shape;  
    float r;
}Circle;

//计算面积

float sq_area(void* thisz)
{
    if (thisz == NULL)
    {
        return -1;
    }
    printf("Square area:\n");
    Square* sp = (Square*)thisz;
    float area = sp->length * sp->length;
    return area;
}
float Cir_area(void* thisz)
{
    if (thisz == NULL)
    {
        return -1;
    }
    printf("Square area:\n");
    Circle * cir = (Circle*)thisz;
    float area = cir->r*cir->r*PI;
    return area;
}

原理:设计一盒函数指针,代表形状的结构体,方形和圆形的结构体,分别计算面积。
将对应的函数赋值给对应的函数指针,再利用形状指针指向圆形和方形结构体的地址,实现动态联编

int main()
{
    Square square;
    memset(&square, 0, sizeof(Square));
    square.length = 10;
    //形状结构体中的函数指针中的面积指针指向计算出来的面积
    square.shape.ops.area = sq_area;
    Circle circle;
    memset(&circle, 0, sizeof(Circle));
    circle.r = 5;
    circle.shape.ops.area = Cir_area;
    Shape *shape = NULL;
    shape = (Shape*)□
    cout << shape->ops.area(&square) << endl;
    shape = (Shape*)&circle;
    cout << shape->ops.area(&circle) << endl;
}

请添加图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值