Menu
Coddy logo textTech

부모 멤버 접근하기

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

이제 구조체 임베딩과 first member 규칙을 이해했으므로, 실용적인 측면에 집중해 보겠습니다. 함수 내부에서 임베드된 parent의 데이터를 읽고 수정하는 방법입니다.

Child 구조체(또는 그 포인터)를 받는 function의 경우, parent의 member에 접근하려면 embedded 구조체를 통해 탐색해야 합니다. 구문은 value로 작업하는지 pointer로 작업하는지에 따라 달라집니다.

typedef struct {
    int id;
    int score;
} Parent;

typedef struct {
    Parent parent;
    char grade;
} Child;

포인터를 사용해 Child를 가리킬 때, 화살표 연산자로 parent에 접근한 다음 점 연산자로 그 멤버에 접근합니다:

void update_score(Child* c, int new_score) {
    c->parent.score = new_score;  // 화살표 다음 점
}

void print_info(Child* c) {
    printf("ID: %d, Score: %d\n", c->parent.id, c->parent.score);
}

(복사로 전달됨)을 사용하며, 전체에서 점을 사용합니다:

void show_id(Child c) {
    printf("ID: %d\n", c.parent.id);  // 점 그다음 점
}

이 연쇄 접근 패턴인 child->parent.member 또는 child.parent.member은 C의 컴포지션 모델에서 상속된 데이터와 상호 작용하는 방식입니다. 실제 상속보다 약간 더 장황하지만, 형식 간의 관계를 명시적이고 명확하게 보여 줍니다.

challenge icon

챌린지

쉬움

embedded struct 내부의 데이터에 Access하고 modify하는 방법을 보여 주는 학생 성적 시스템을 만들어 보겠습니다. Student가 embedded Person을 포함하는 계층 구조를 만들고, child를 통해 parent의 데이터와 함께 작동하는 function을 작성합니다.

코드를 세 개의 파일로 구성합니다.

  • student.h: include guard를 사용하여 struct 계층 구조를 Define합니다. name(50 characters의 character array)과 age(integer)를 포함하는 Person struct를 Create합니다. 그런 다음 Person을 첫 번째 member로 embedded하고 grade field(점수를 나타내는 integer)를 추가하는 Student struct를 Define합니다. Student*와 new age value를 받는 set_person_age function과, Student*를 받아 all information을 display하는 print_student function을 Declare합니다.
  • student.c: 두 function을 모두 Implement합니다. set_person_age function은 embedded Person struct 내부의 age를 modify해야 합니다. 여기에서 arrow-then-dot syntax(s->person.age)를 연습합니다. print_student function은 embedded person과 student 자체의 all fields에 Access하여 display해야 합니다.
  • main.c: Student variable을 Create하고 모든 field를 Initialize합니다. 그런 다음 set_person_age를 사용하여 embedded person's age를 update하고, print_student를 Call하여 result를 display합니다.

네 가지 input을 받습니다. 학생의 name(string), initial age(integer), grade(integer), 그리고 new age(function을 통해 update할 integer)입니다.

main file에서 initial values로 student를 Create한 다음, set_person_age를 Call하여 age를 new value로 변경하고, 마지막으로 print_student를 Call하여 updated information을 display합니다.

Output은 다음과 같아야 합니다.

Name: Emma
Age: 21
Grade: 85

여기서 Emma는 name이고, 21은 initial age가 아닌 updated age이며, 85는 grade입니다. 여기서 핵심적으로 배울 내용은 embedded struct를 탐색하여 parent의 member를 모두 read하고 write하는 방법입니다.

직접 해보기

#include <stdio.h>
#include <string.h>
#include "student.h"

int main() {
    char name[50];
    int initial_age, grade, new_age;
    
    // 입력 읽기
    fgets(name, 50, stdin);
    name[strcspn(name, "\n")] = '\0';  // 개행 제거
    scanf("%d", &initial_age);
    scanf("%d", &grade);
    scanf("%d", &new_age);
    
    // TODO: Student 변수 생성
    
    // TODO: student의 모든 필드 초기화
    // - strcpy를 사용하여 name을 내장된 person의 name에 복사
    // - 내장된 person의 age를 initial_age로 설정
    // - student의 grade 설정
    
    // TODO: set_person_age를 호출하여 age를 new_age로 업데이트
    
    // TODO: print_student를 호출하여 결과 표시
    
    return 0;
}
quiz icon실력 점검

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

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

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