[완료] C를 OOP처럼 구성하고자 하였을 때 this 키워드의 구현방법

disint의 이미지

C를 OO적으로 접근하여 구현하는 문서들이 보여 셈플 코드를 작성하던 도중 this 키워드의 부재로 인한 문제가 있어 질문을 해봅니다.

OOPC 관련 문서들을 보면 "struct를 통해 class를 구현한다"는 내용이 다수였습니다. 그렇게 구현하던 도중 struct는 class와 달리

맴버함수를 지니지 못하므로 함수 포인터를 통해 함수를 연결했을 경우, 구조체 내의 변수를 참조할 수 없는 문제가 생겼습니다. 이로

인해서 self pointer라는 개념으로 각각의 함수에 객채로 생성한 구조체의 포인터값을 넘겨서 함수를 수행하는 방법이 많이 나와 있었

습니다.

this 키워드나 개념을 잡을 수 있는게 있다면 self pointer를 넘기지 않고도 구조체 내부의 변수등을 접근할 수 있을 것으로 생

각되어 혹시 구현할 수 있는 방법이 있나 싶어서 질문을 해봅니다.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
typedef struct string{
    //Class variable
    char *data;
    int length;
 
    //Class methods
    int (*get_length)(struct string *this);
    void (*add_string)(struct string *this, char *str);
    void (*change_string)(struct string *this, char *str);
    void (*show_string_info)(struct string *this);
}string;
 
int get_length(string *this)
{
    return this->length;
}
 
void add_string(string *this, char *str)
{
   strcat(this->data,str);
   this->length = strlen(this->data);
}
 
void change_string(string *this, char *str)
{
    if (NULL != this->data);
	free(this->data);
 
    this->data = strdup(str);
    this->length = strlen(this->data);
 
}
 
void show_string_info(string *this)
{
    printf("String : %s\n",this->data);
    printf("Length : %d\n",this->length);
}
 
string *create_string(char *data)
{
    string *s;
    s = (string *)malloc(sizeof(string));
    s->get_length = get_length;
    s->add_string = add_string;
    s->change_string = change_string;
    s->show_string_info = show_string_info;
 
    s->data = strdup(data);
    s->length = strlen(s->data);
 
    return s;
}
 
void delete_string(string *this)
{
    if (NULL != this->data)
	free(this->data);
    if (NULL != this)
	free(this);
}
 
 
int main()
{
 
    string *first = NULL, *second = NULL;
 
    first = create_string("abcdefg");
    second = create_string("EEE");
 
    first->show_string_info(first);
 
    first->change_string(first, "12345678");
    first->show_string_info(first);
 
    first->add_string(first,second->data);
    first->show_string_info(first);
 
    first->change_string(first,"abc");
    first->show_string_info(first);
 
    delete_string(first);
    delete_string(second);
}
winner의 이미지

C++도 사실 this를 넘깁니다.
즉 obj.met(param) 라는 source는 사실 met(&obj, param) 형태로 전환된다고 보는게 맞습니다.

또하나 생각해 볼 수 있는 것으로 Python은 this에 해당하는 self를 관용적으로 매개변수로 받으라고 합니다.

class Klass:
  def met(self, param):
    pass

로 정의하고

obj = Klass()
obj.met(param)

형태로 사용합니다.

문법이 다를 뿐 내부원리는 이런 형태이기에 C 문법을 유지하면서 원하시는 바를 이루기는 어려울 거라고 생각합니다.

disint의 이미지

답변 감사합니다.
c++에서 내부적으로 this를 저렇게 넘긴다는 사실은 처음 알았습니다.
덕분에 포기할 수 있게되네요. 감사합니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.