언어 자료구조 알고리즘/C언어 예제

C언어에서의 캡슐화, C언어 소스

언제나휴일 2016. 4. 3. 18:42
반응형

C언어에서의 캡슐화, C언어 소스


캡슐화는 여러 멤버를 하나의 형식으로 묶는 것을 말합니다. C언어에서의 캡슐화는 주로 구조체를 이용합니다

그리고 C언어의 구조체는 멤버 변수(멤버 변수, 멤버 데이터) 구성합니다.

간단한 예를 들어봅시다.

 

유닛은 일련 번호와 이름 , 체력 데이터를 갖습니다.
그리고 유닛을 동적으로 생성하며 훈련, 휴식할 있습니다.
유닛의 멤버 데이터를 가져오기 있는 접근자가 있습니다.
유닛의 체력 데이터를 설정자가 있습니다.
체력은 최소(0) 체력, 최대(100) 최력 사이에서 변할 있습니다.



C언어에서 캡슐화.c

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

 

#define MAX_HP    100//최대 HP

#define MIN_HP    0//최소 HP

 

typedef struct Unit//유닛 구조체 정의

{

    int seqno;//일련번호

    char *name;//이름

    int hp;//hp

}Unit;

 

Unit *NewUnit(int seqno, const char *name);//Unit 동적 생성

void DeleteUnit(Unit *unit);//Unit 메모리 해제

void Training(Unit *unit, int cnt);//훈련하다.

void Relax(Unit *unit, int cnt);//휴식하다.

int GetSeqNo(Unit *unit); //일련번호 접근자

const char *GetName(Unit *unit);//이름 접근자

int GetHP(Unit *unit);//hp 접근자

 

 

void Initialize(Unit *unit, int seqno, const char *name);//초기화

void SetHP(Unit *unit, int hp);//hp 설정자

 

Unit *NewUnit(int seqno, const char *name)

{

    Unit *unit = (Unit *)malloc(sizeof(Unit));

    Initialize(unit, seqno, name);

    return unit;

}

void Initialize(Unit *unit, int seqno, const char *name)

{

    int len;

 

    unit->seqno = seqno;

    len = strlen(name) + 1;

    unit->name = (char *)malloc(len);

    strcpy_s(unit->name, len, name);

    unit->hp = MIN_HP;

}

 

void DeleteUnit(Unit *unit)

{

    free(unit->name);

    free(unit);

}

 

void Training(Unit *unit, int cnt)

{

    printf("%d 유닛, %d번 훈련\n", unit->seqno, cnt);

    SetHP(unit, unit->hp + cnt);

}

void Relax(Unit *unit, int cnt)

{

    printf("%d번 유닛, %d번 휴식\n", unit->seqno, cnt);

    SetHP(unit, unit->hp - cnt);

}

void SetHP(Unit *unit, int hp)

{

    if (hp>MAX_HP)

    {

        hp = MAX_HP;

    }

    if (hp<MIN_HP)

    {

        hp = MIN_HP;

    }

    unit->hp = hp;

}

 

int GetSeqNo(Unit *unit)

{

    return unit->seqno;

}

const char *GetName(Unit *unit)

{

    return unit->name;

}

int GetHP(Unit *unit)

{

    return unit->hp;

}

void ViewUnit(Unit *unit)

{

    printf("<%d, %s> hp:%d\n", GetSeqNo(unit), GetName(unit), GetHP(unit));

}

 

 

int main(void)

{

    Unit *unit = 0;

 

    unit = NewUnit(1, "홍길동");

    ViewUnit(unit);

    Training(unit, 10);

    ViewUnit(unit);

    Relax(unit, 5);

    ViewUnit(unit);

    Training(unit, 100);

    ViewUnit(unit);

    Relax(unit, 200);

    ViewUnit(unit);

    printf("%d 유닛, %d번 훈련\n", unit->seqno, 200);

    unit->hp += 200;

    ViewUnit(unit);

    DeleteUnit(unit);

    return 0;

}

 

C언어의 구조체는 멤버의 가시성을 설정하는 접근 지정자 문법이 없습니다.
이러한 이유로 제공하는 제공한 함수를 호출하지 않고 직접 멤버에 접근할 있습니다.
이는 간단하게 접근할 있어 장점처럼 보입니다.
하지만 특정 상태를 유지해야 하는 데이터 신뢰성을 추가할 논리적 버그가 자주 발생할 있습니다.

예제의 main 테스트 코드에서 직접 hp 멤버에 접근하여 값을 설정하였을 최소 체력~최대 체력을 벗어날 있습니다.

 

이렇게 C언어의 구조체가 갖는 신뢰성의 문제를 해결하기 위해 OOP 언어에서 클래스에서는 멤버들의 접근 가시성을 설정하는 접근 지정자를 제공하고 있습니다.


반응형