C语言模拟面向对象语言

面向对象是一种思想,并没有规定死怎么去实现。这里我用C语言这种面向过程的语言来模拟了一下。暂时解决了封装,方法的重载,继承和多态还没实现。

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

struct Student{
    int num;//声明类成员属性
    char* name;
    int sex;
    void (*Student)(struct Student*);//声明无参构造
    void (*Student_int_str_int)(int,char*,int,struct Student*);//声明有参构造
    int (*getNum)(struct Student*);//声明成员方法
    int(*setNum)(int,struct Student*);
};

void Student(struct Student *this){//无参构造
    this->num = 0;
    this->name = NULL;
    this->sex = 0;
}

void Student_int_str_int(int num , char* name , int sex , struct Student *this){// 重载后的有参构造
    this->num = num;
    this->name = name;
    this->sex = sex;
}

int getNum(struct Student *this){//getter方法
    return this->num;
}

void setNum(int num,struct Student *this){//setter方法
    this->num=num;
}

int main(){
    /*等价于Student stu = new Student(123,"zhangsan",45);*/
    struct Student * stu;//定义一个stu对象,这个对象只为成员变量分配内存空间
    struct Student * this = (struct Student*)malloc(sizeof(struct Student));//在堆中动态开辟内存空间
    Student_int_str_int(18,"zhangsan",45,this);//调用有参构造,由编译器加入的代码
    stu = this;//this的引用赋给stu
    stu->getNum = getNum;//将结构体的方法指针指向对应的方法
    printf("stu.getNum()=%d\n",stu->getNum(stu));//通过对象(对象指针)调用方法
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值