C语言:矩形c_oop

main.c

#include <stdio.h>
#include <stdlib.h>

// 定义矩形结构体
typedef struct {
    double width;
    double height;
    // 函数指针成员,模拟方法
    double (*area)(void *self);
    double (*perimeter)(void *self);
} Rectangle;

// 计算矩形面积的方法
double calculate_area(void *self) {
    Rectangle *rect = (Rectangle *)self;
    return rect->width * rect->height;
}

// 计算矩形周长的方法
double calculate_perimeter(void *self) {
    Rectangle *rect = (Rectangle *)self;
    return 2 * (rect->width + rect->height);
}

// 初始化矩形对象
Rectangle *Rectangle_create(double width, double height) {
    Rectangle *rect = malloc(sizeof(Rectangle));
    if (rect != NULL) {
        rect->width = width;
        rect->height = height;
        rect->area = calculate_area;
        rect->perimeter = calculate_perimeter;
    }
    return rect;
}

// 销毁矩形对象
void Rectangle_destroy(Rectangle *rect) {
    free(rect);
}

int main() {
    // 创建矩形对象
    Rectangle *my_rect = Rectangle_create(5.0, 3.0);

    // 使用对象方法计算面积和周长
    double area = my_rect->area(my_rect);
    double perimeter = my_rect->perimeter(my_rect);

    printf("Rectangle with width %.2f and height %.2f\n", my_rect->width, my_rect->height);
    printf("Area: %.2f\n", area);
    printf("Perimeter: %.2f\n", perimeter);

    // 销毁对象
    Rectangle_destroy(my_rect);

    return 0;
}

Makefile

rectangle : main.c
	gcc main.c -o rectangle

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值