C로 C++ 흉내내기?

handrake의 이미지

안녕하세요. 실제 프로그래밍에서는 전혀 쓸모가 없을지도 모르는 것이지만 순수히 궁금해서 질문드립니다.
여기 kldp에서도 C로 C++를 흉내낼수 있다는 글을 많이 보았는데요, 어떻게 하면 될지 생각해 보고
나름대로 클래스를 구현해보았습니다.

 
#include<stdio.h>

void *this = 0;
void inc_one();
void dec_one();

typedef void (*void_func)(void);

typedef struct my_str {
        int iLen;
        void_func inc;
        void_func dec;
}my_str;

my_str* init_my_str()
{
        my_str *new_my_str = (my_str*) malloc(sizeof(my_str));
        new_my_str->inc = &inc_one;
        new_my_str->dec = &dec_one;
        new_my_str->iLen = 0;
        return new_my_str;
}

void inc_one()
{
        ((my_str*)this)->iLen++;
}

void dec_one()
{
        ((my_str*)this)->iLen--;
}

main()
{
        my_str *a = init_my_str();
        this = a;
        printf("a->iLen = %d\n", a->iLen);
        a->inc();
        printf("a->iLen = %d\n", a->iLen);
}

여기서 궁금한 점은 저렇게 this=a; 를 매번 지정해주지 않아도 어떤 struct에서 불렀는지
알 수 있는 방법이 있는지 입니다. 이렇게 하는것보다 더 좋은 방법이 있으면 제시해 주시면 고맙겠습니다 ^^

ㅡ,.ㅡ;;의 이미지

dondek wrote:
돼지군 wrote:
완전히 알려지지 않은 구조체

C 언어로 은닉 (Encapsulation) 을 구현하는 쓸모있는 방법입니다.
비슷한 방법이 C++ 에서 재번역 의존성 제거법으로도 쓰이고요.
(Herb Sutter 님의 Exceptional C++ 참고)

List of "foo.c" :

#include "bar.h"

int main()
{
   BAR *bar = create_bar();
   use_bar(bar);
   remove_bar(bar);
   return 0;
}

List of "bar.c" :

#include "bar.h"

struct BAR_
{
  int somedata1;
  int somedata2;
  void *memory;
};
typedef struct BAR_ BAR;

BAR *create_bar() { static BAR b; return &b; }
void use_bar(BAR *) {  }
void remove_bar(BAR *) { }

List of "bar.h" :

struct BAR_;

struct BAR_ *create_bar();
void use_bar(struct BAR_ *);
void remove_bar(struct BAR_ *);

C 써본 지 하도 오래되어 잘 모르겠지만,
대충 이 정도면 충분한 것으로 알고 있습니다.
이의 제기 해주세요.

create_bar() 함수에서 static으로 만들게 되어있는데 그렇다면 이 함수를 사용해서 여러개의 BAR 객체(객체라고까지 할 건 없지만)를 만들수는 없겠네요? static 변수의 주소를 되돌리게 되어있으니 말이예요.

저코드는 은닉혹은 의존성이 제거되지 않는데...


----------------------------------------------------------------------------

cronex의 이미지

어라... 이 글 아직 명예의 전당 안 올라갔나요?

------------------------------------------------------------
이 멍청이~! 나한테 이길 수 있다고 생각했었냐~?
광란의 귀공자 데코스 와이즈멜 님이라구~!

페이지