'재미'가있는 경우 포인터 기능을 사용하여 C++
멤버 함수를 C
에 에뮬레이트하기로했습니다.포인터 함수를 사용하여 C 구조체의 멤버 함수를 에뮬레이트
obj.h :
#ifndef OBJ_H
#define OBJ_H
#include <stdlib.h>
#include <stdio.h>
struct Obj{
struct pObjVar* pVar;
void (*read)(struct Obj*);
void (*set) (struct Obj*, int);
};
struct Obj* newObj();
void deleteObj(struct Obj** obj);
#endif
obj.c :
#include "obj.h"
void readValue(struct Obj* this_);
void setValue (struct Obj* this_, int mValue_);
struct pObjVar{
int mValue;
};
struct Obj* newObj(){
struct Obj* tmp = (struct Obj*) malloc(sizeof(struct Obj));
tmp->pVar = (struct pObjVar*) malloc(sizeof(struct pObjVar));
tmp->pVar->mValue = 0;
tmp->read = readValue;
tmp->set = setValue;
return tmp;
}
void deleteObj(struct Obj **obj){
free((*obj)->pVar); (*obj)->pVar = NULL;
free((*obj)); *obj = NULL;
}
void readValue(struct Obj *this_){
printf("Value = %d\n",this_->pVar->mValue);
}
void setValue(struct Obj *this_, int mValue_){
this_->pVar->mValue = mValue_;
}
의 main.c :
#include "obj.h"
int main(void)
{
struct Obj* a = newObj();
a->set(a, 10);
a->read(a);
deleteObj(&a);
return 0;
}
출력 :
>./a.out
Value = 10
다음은 간단한 코드
그러나이 작업을 수행 할 때 암시 적으로 this
포인터를 내 멤버 함수에 명시 적으로 전달하여 포인터 역할을 에뮬레이션해야한다고 생각했습니다. 이것은 잘 동작 합니다만, 모든 것이 이상하게 보일뿐입니다! 나는 개체를 전달하고 싶었다면
, 왜 멤버 함수와 같은 기능을 구현하는 것이? 내가 찾은 유일한 대답은 통합 인터페이스를 원하지만 다양한 구현이 필요한 경우 일 것입니다. (뭔가가 과 비슷한 ~ C++
가상 함수?)
회원 기능을 에뮬레이션하는 다른 이유는 무엇입니까? 또한 명시 적으로 this_
포인터를 전달할 수있는 방법이 있습니까?
편집 : 개체를 전달할 때 원본 코드에 문제가있었습니다. 실수로 read/set
함수를 사용하여 &a
을 사용하고있었습니다. 포인터를 NULL
내부적으로 설정하려면 deleteObj
에만 필요합니다.
당신은 기능, 즉'의 Obj **'포인터의 _address_을 전달하고 있습니다. 함수 호출에서'&'를 건너 뛰십시오. –
@ JoachimPileborg : 정확합니다.내 편집 – GradGuy
을 보았습니다. 복잡한 접근 방식을 사용하는 유사한 접근법과 구조체에 대한 포인터 대신에 불투명 한 typedef'ed int 값을 사용하여 병합을 추가해야만했습니다. 말할 필요도없이 디버깅/유지 관리가 악몽이었습니다! – SirDarius