๐Ÿงธ ๊ฐ์ฒด์ง€ํ–ฅ C - ๋ฉค๋ฒ„ํ•จ์ˆ˜

์˜ค์ธ๊ทœยท2020๋…„ 5์›” 31์ผ
5
post-custom-banner

์˜ค๋Š˜์€ ๋ฉค๋ฒ„ํ•จ์ˆ˜์—๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๋ ค๊ณ ํ•œ๋‹ค.

๋‹ค๋ฅธ ๊ฐ์ฒด์ง€ํ–ฅ์–ธ์–ด์—์„œ๋Š” ๋‹ค์Œ๊ณผ๊ฐ™์ด ๊ฐ์ฒด.๋ฉ”์†Œ๋“œ()๋ฅผ ํ†ตํ•ด์„œ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ–ˆ์—ˆ๋‹ค.

Student jacky = new Student("Jacky", "CSE", 4.4);
jacky.say_hi();

์ด์ „์˜ ํฌ์ŠคํŒ…์—์„œ ์ •์˜ํ–ˆ๋˜ student_t๋ฅผ ๋‹ค์‹œ ๊ฐ€์ ธ์˜ค๊ฒ ๋‹ค.

typedef struct student {
    char* name;
    char* major;
    float gpa;
} student_t;

student_t* new_student(char* name, char* major, float gpa) {
    student_t* this = malloc(sizeof(student_t));
    
    this->name = strdup(name);
    this->major = strdup(major);
    this->gpa = gpa;
    
    return this;
}

void del_student(student* this) {
    free(this->name);
    free(this->major);
    free(this);
}

์ด ๊ตฌ์กฐ์ฒด๋ฅผ ์ง€์›ํ•˜๋Š” say_hi()ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด๋ณด์ž.

void student_say_hi(student_t* this) {
    if (this->gpa > 4.0) { // ๊ฐ์ฒด๊ฐ€ ์ƒํƒœ๋ฅผ ๊ฐ–๋Š”๋‹ค!
        printf("๋‚˜๋Š” %s๋‹ค.\n", this->name);
        return;
    }
    printf("์•ˆ๋…•ํ•˜์„ธ์š” ์ €๋Š” %s๋ฅผ ์ „๊ณตํ•˜๊ณ ์žˆ๋Š” %s๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๋ฐ˜๊ฐ‘์Šต๋‹ˆ๋‹ค.\n", this->major, this->name);
}

ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ student_t* this๋ฅผ ๋„ฃ์–ด์ฃผ๋Š”๊ฒŒ ๊ฑฐ์Šฌ๋ฆด ์ˆ˜ ์žˆ๋Š”๋ฐ ํŒŒ์ด์ฌ์—์„œ self๊ณ„์† ๋ถ™์ด๋Š”๊ฒƒ์ฒ˜๋Ÿผ ํ•ด์•ผ๋œ๋‹ค. C์–ธ์–ด๋Š” ๊ฐ์ฒด์ง€ํ–ฅ ํŒจ๋Ÿฌ๋‹ค์ž„์„ ๊ณ ๋ คํ•ด์„œ ์„ค๊ณ„ํ•œ ๊ฐ์ฒด์ง€ํ–ฅ ์–ธ์–ด๊ฐ€ ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— ์–ด์ฉ” ์ˆ˜ ์—†๋‹ค.

student_t* jacky = new_student("Jacky", "CSE", 4.4);
student_say_hi(jacky);

๋ฉค๋ฒ„ํ•จ์ˆ˜ ํ˜ธ์ถœ์„ ํ†ตํ•˜๋Š”๊ฒŒ ์•„๋‹ˆ๋ผ์„œ ๋ญ”๊ฐ€ ๋ง›์ด ์•ˆ๋‚œ๋‹ค. ๊ตฌ์กฐ์ฒด์— ํ•จ์ˆ˜ํฌ์ธํ„ฐ๋ฅผ ํ†ตํ•ด์„œ ๋ฉค๋ฒ„ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด๋ณด์ž.

extern void student_say_hi(student_t* this);

struct student {
    char* name;             // ์ด๋ฆ„
    char* major;            // ์ „๊ณต
    float gpa;              // ํ•™์ 
    void (*say_hi) (struct student *);  // ์ž๊ธฐ์†Œ๊ฐœ
};

student_t* new_student(char* name, char* major, float gpa) {
    student_t* this = malloc(sizeof(student_t));

    this->name = name;
    this->major = major;
    this->gpa = gpa;
    this->say_hi = student_say_hi;

    return this;
}

student_t *jacky = new_student("Jacky", "CSE", 4.4);
jacky->say_hi(jacky); // this๋ฅผ ํ•ญ์ƒ ๋„˜๊ฒจ์ค˜์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ถˆํŽธํ•˜๋‹ค.

์ด๋ ‡๊ฒŒ ๋ฉค๋ฒ„ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค ์ˆ˜๋Š” ์žˆ๋‹ค. ๊ทผ๋ฐ ๊ฒ๋‚˜ ๋ถˆํŽธํ•˜๋‹ค. ์ง€๊ฐ€ ํ˜ธ์ถœํ•ด๋†“๊ณ  ์ง€๋ฅผ ์ธ์ž๋กœ ๋„˜๊ฒจ์คŒ
์‹ค์ œ๋กœ C์—์„œ ๊ฐ์ฒด์ง€ํ–ฅ์„ ํ•˜๋Š” ์ฝ”๋“œ๋“ค์„ ๋ณด๋ฉด ๋ฉค๋ฒ„ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์•„๋ž˜์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋Š”๊ฒƒ์ด 100์ค‘์— 99์ด๋‹ค.

student_say_hi(jacky);

๊ทธ๋ƒฅ ๋ฉค๋ฒ„ํ•จ์ˆ˜๋ฅผ ํ•จ์ˆ˜ํฌ์ธํ„ฐ๋ฅผ ํ†ตํ•ด์„œ ์–ด๋–ป๊ฒŒ ๊ตฌํ˜„ํ•˜๋Š”์ง€ ์ •๋„๋งŒ ์ดํ•ดํ•˜๊ณ  ๋„˜์–ด๊ฐ€๋ฉด ์ถฉ๋ถ„ํ•˜๋‹ค. ์ง„์งœ ๋…ธ์“ธ๋ชจ๋‹ค.

profile
๋„ค์ด๋ฒ„๋žฉ์Šค ํ”„๋ก ํŠธ์—”๋“œ ๊ฐœ๋ฐœ์ž
post-custom-banner

1๊ฐœ์˜ ๋Œ“๊ธ€

comment-user-thumbnail
2020๋…„ 6์›” 19์ผ

๊ฐ‘์ž๊ธฐ ๋‚œ์ด๋„ ๋‚ด๋ ค๊ฐ€์„œ ํ๋ญ‡

๋‹ต๊ธ€ ๋‹ฌ๊ธฐ