Menu
Coddy logo textTech

'Self' 포인터

Coddy C 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 7번째.

Python이나 Java와 같은 객체 지향 언어에서는 object.method()를 호출하면 언어가 자동으로 객체 자체를 메서드에 전달합니다. C에서는 첫 번째 인수로 struct에 대한 pointer를 전달하여 이를 수동으로 수행해야 합니다.

이 포인터는 관례적으로 self(Python에서 차용) 또는 this(C++에서 차용)라는 이름을 사용합니다. 이 포인터를 통해 function이 struct의 데이터에 접근하여 이를 읽거나 수정할 수 있습니다.

typedef struct {
    int health;
} Player;

void player_take_damage(Player *self, int amount) {
    self->health -= amount;
}

self 포인터는 function이 메서드처럼 동작하도록 만드는 것입니다. 이 포인터는 어떤 player를 수정해야 하는지 알고 있습니다. 이것이 없다면 function은 특정 struct 인스턴스에 액세스할 방법이 없습니다. 이 function을 호출할 때는 struct의 주소를 전달합니다.

Player hero = {100};
player_take_damage(&hero, 25);
// hero.health는 이제 75입니다

구조체를 직접 전달하는 대신 pointer를 사용하는 것은 수정에 필수적입니다. 구조체를 값으로 전달하면 function은 복사본을 받게 되며, 변경 사항은 function이 반환될 때 손실됩니다. pointer는 변경 사항이 원래 struct에 유지되도록 합니다.

challenge icon

챌린지

쉬움

경과한 seconds를 추적하는 Timer 모듈을 만들어 보겠습니다. 함수가 메서드처럼 동작하도록 하여 struct의 내부 상태를 수정하는 "self" pointer 패턴을 using하는 방법을 연습합니다.

세 개의 파일을 만듭니다:

  • timer.h: 하나의 int seconds member를 가진 Timer struct를 Declare합니다. 또한 두 function을 Declare합니다. timer_tick은 Timer에 대한 pointer를 takes하고 지정된 수의 seconds를 더하며, timer_reset은 Timer에 대한 pointer를 takes하고 seconds를 다시 zero로 설정합니다. TIMER_H symbol을 사용하여 include guards를 사용합니다.
  • timer.c: 두 function을 모두 Implement합니다. timer_tick function은 Timer *selfint amount를 accept한 다음, amount를 timer의 seconds에 더해야 합니다. timer_reset function은 Timer *self를 accept하고 its seconds를 zero로 설정해야 합니다.
  • main.c: Timer를 Create하고, 이에 대한 작업을 수행한 다음, 결과를 표시합니다.

두 개의 정수 입력을 받습니다. timer의 initial seconds와 tick을 통해 더할 amount입니다.

main 파일에서 다음을 수행합니다:

  1. initial seconds 값으로 Timer를 initialize합니다
  2. 지정된 amount를 더하기 위해 timer_tick을 Call합니다
  3. current seconds를 Print합니다
  4. timer를 reset하기 위해 timer_reset을 Call합니다
  5. seconds를 다시 Print합니다 (0이어야 합니다)

결과를 다음 format으로 Print합니다:

After tick: {seconds}
After reset: {seconds}

예를 들어 initial 값이 30이고 15 seconds를 더하면 출력은 다음과 같습니다:

After tick: 45
After reset: 0

직접 해보기

#include <stdio.h>
#include "timer.h"

int main() {
    int initial_seconds, amount_to_add;
    scanf("%d", &initial_seconds);
    scanf("%d", &amount_to_add);
    
    // TODO: Timer를 생성하고 initial_seconds로 초기화하세요
    
    // TODO: timer_tick을 호출하여 amount_to_add 초를 더하세요
    
    // TODO: 현재 초를 다음 형식으로 출력하세요: "After tick: {seconds}"
    
    // TODO: timer_reset을 호출하여 타이머를 재설정하세요
    
    // TODO: 초를 다시 다음 형식으로 출력하세요: "After reset: {seconds}"
    
    return 0;
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 C 컴파일러