Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1016934
  • 博文数量: 146
  • 博客积分: 3444
  • 博客等级: 中校
  • 技术积分: 1602
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-21 15:18
文章分类

全部博文(146)

文章存档

2014年(9)

2013年(3)

2012年(6)

2011年(44)

2010年(38)

2009年(46)

分类: C/C++

2011-08-23 15:32:22

#include
#include
//本程序用于研究用C中的struct结构模拟C++中的类,以函数指针的方式为struct添加对成员函数的支持
//定义一个“类”
typedef  struct _myclass 
int a;
int b;
int (*max)(int c,int d);
int (*min)(int c,int d);
int (*addab)(struct _myclass *t);
} myclass; 

//类成员函数1,2的操作数与类成员变量无关,那么函数的定义方法和C++中一样
int mbmax(int a,int b){
return (a>b?a:b);
}
int mbmin(int a,int b){
return (b
}
//类成员函数的操作数与类成员变量有关,那么该函数需要当前类实例的地址做为输入,有没有高手可以不用当前类实例的地址就可以解决这个问题?
//进一步需要指出的是,如果一个成员函数通过调用其它成员函数间接操作了类成员变量,那么这个函数也需要传入当前的类实例地址
//唉,有没有办法自动获得这个this指针呢。。。。。。。
int mbaddab(myclass *t){
return t->a+t->b;
}

//相当于C++的类构造函数,用于创建一个类实例,并初始化这个类实例,构造函数命名采用 类名init 的方式。
myclass * myclassinit(){
myclass *t=(myclass  *) malloc(sizeof(myclass));
t->a=1;
t->b=1;
t->max=mbmax;
t->min=mbmin;
t->addab=mbaddab;
return t;
}

int main(){
myclass *tt=myclassinit();  //类的创建方法只要一条语句就可以完成,达到了和C++中new类似的效果
printf("the max number is %d\n",tt->max(4,8));
printf("the min number is %d\n",tt->min(4,8));
printf("a plus b is %d\n",tt->addab(tt));
return 0;
}

欢迎大家留言一起讨论。

阅读(3826) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

wujiajia2011-08-26 14:27:22

this 指针是编译器级别的事情,真不好实现