c++ class功能 :
class Test {
private :
int i ;
int j;
public :
Test (int v1 = 0, int v2 = 0) {
i = v1;
j = v2;
}
int getI () {
return i;
}
int getJ () {
return j;
}
int add(int value) {
return i + j + value;
}
~Test() {
//没有申请空间啥都不用干
}
};
利用c来实现:
head.h
#ifndef _HEAD_H
typedef void demo;
demo* demo_init(int i, int j); //模拟构造函数
int getI(demo *pthis);
int getJ(demo *pthis);
int add(demo *pthis, int value);
void free_demo(demo *pthis);
#define _HEAD_H
#endif
head.c
#include <stdlib.h>
#include "head.h"
typedef struct class_demo{
int a;
int b;
}class_demo;
demo* demo_init(int i, int j) {
class_demo *p = (class_demo *)malloc(sizeof(class_demo));
if (p != NULL) {
p->a = i;
p->b = j;
}
return p;
}
int getI(demo *pthis) {
class_demo *p = (class_demo *) pthis;
return p->a;
}
int getJ(demo *pthis) {
class_demo *p = (class_demo *) pthis;
return p->b;
}
int add(demo *pthis, int value) {
class_demo *p = (class_demo *) pthis;
return p->a + p->b + value;
}
void free_demo(demo *pthis) {
free(pthis);
}
main.c
#include<stdio.h>
#include "head.h"
int main() {
demo *p = demo_init(1, 2);
printf("a = %d\n", getI(p));
printf("b = %d\n", getJ(p));
printf("add = %d\n", add(p, 5));
return 0;
}
这样写有一个好处,可以理解c++ this指针的工作机制,在c中,pthis就是this指针,代表了函数的首地址。
网友评论