面向对象是一种思想,并没有规定死怎么去实现。这里我用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;
}