Ex090301) Human 구조체
아래 코드를 따라서 작성해봅시다. 따라 작성한 소스코드의 실행 결과를 예측해보고, 예측 결과와 실행 결과를 비교해봅시다.
// Main.cpp
#include <stdlib.h>
struct Human
{
float Height;
float Weight;
size_t Age;
};
typedef struct Human Human_t;
int main(void)
{
Human_t* Park = (Human_t*)malloc(1 * sizeof(Human_t));
free(Park);
Park = NULL;
return 0;
}
객체지향 프로그래밍의 시작
위 예제가 별거 아닌것처럼 보이지만, 객체지향 프로그래밍의 시작과도 같습니다. Park이라는 Human_t 객체를 만들어 낸 예제입니다. 객체지향 프로그래밍 언어는 객체 간의 상호작용에 중점을 둔 언어입니다. 지금까지 배운 내용으로 객체지향 프로그래밍을 살짝 맛보도록 해봅시다.
구조체에 멤버 변수만 선언 할 수 있는건 아닙니다.
객체지향 프로그래밍으로 넘어가면서 구조체에는 멤버 함수도 선언 할 수 있습니다.
Ex090302) 멤버 함수 1
아래 코드를 따라서 작성해봅시다. 따라 작성한 소스코드의 실행 결과를 예측해보고, 예측 결과와 실행 결과를 비교해봅시다.
// Main.cpp
#include <stdio.h>
#include <stdlib.h>
struct Human
{
float Height;
float Weight;
size_t Age;
void SayHello(void)
{
printf("Hello!\\n");
return;
}
};
typedef struct Human Human_t;
int main(void)
{
Human_t* Park = (Human_t*)malloc(1 * sizeof(Human_t));
Park->SayHello();
free(Park);
Park = NULL;
return 0;
}
Ex090303) 멤버 함수 2 [중요 샘플 코드]
아래 코드를 따라서 작성해봅시다. 따라 작성한 소스코드의 실행 결과를 예측해보고, 예측 결과와 실행 결과를 비교해봅시다.
// Main.cpp
#include <stdio.h>
#include <stdlib.h>
struct Human
{
float Height;
float Weight;
size_t Age;
void SayHello(void)
{
printf("Hello!\\n");
return;
}
void SayMyInfo(void)
{
printf("My Height is %.1f.\\n", Height);
printf("My Weight is %.1f.\\n", Weight);
printf("My age is %zu.\\n\\n", Age);
return;
}
};
typedef struct Human Human_t;
int main(void)
{
Human_t* Park = (Human_t*)malloc(1 * sizeof(Human_t));
Park->Height = 173.f;
Park->Weight = 70.f;
Park->Age = 19;
Park->SayHello();
Park->SayMyInfo();
free(Park);
Park = NULL;
return 0;
}
Ex090304) 클래스 만들어보기
현실에 있는 어떤 사물을 구조체로 정의해보고, 그 구조체의 객체를 생성 및 해제 해봅시다. 예컨대, 비둘기라던가 고양이라던가…
// Main.cpp
#include <stdio.h>
#include <stdlib.h>
struct Racket
{
size_t Tension;
size_t Weight;
void PrintRecommend(int type)
{
switch (type)
{
case 1:
printf("Head heavy\n");
break;
case 2:
printf("Even balance\n");
break;
case 3:
printf("Head light\n");
break;
default:
printf("잘못된 입력입니다.");
break;
}
return;
}
};
typedef struct Racket Racket_t;
int main(void)
{
Racket_t* MyRacket = (Racket_t*)malloc(1 * sizeof(Racket_t));
MyRacket->Tension = 28;
MyRacket->Weight = 84;
printf("원하는 플레이 스타일을 골라주세요.\n");
printf("1.속공에 약하지만 강력한 한방공격.\n");
printf("2.수비, 공격 모두 밸런스맞게.\n");
printf("3.힘은 약하지만 빠른공격과 수비.\n");
int A;
scanf_s("%d", &A);
MyRacket->PrintRecommend(A);
free(MyRacket);
MyRacket = NULL;
return 0;
}'C' 카테고리의 다른 글
| [내배캠자습]C언어 챕터 9-4 : enum (0) | 2026.03.29 |
|---|---|
| [내배캠자습]C언어 챕터 9-2 : typedef (0) | 2026.03.29 |
| [내배캠자습]C언어 챕터 9-1 : 구조체 (0) | 2026.03.29 |
| [내배캠자습]C언어 챕터 8-2 : 동적할당과 메모리 소유권 문제 (0) | 2026.03.29 |
| [내배캠자습]C언어 챕터 8-1 : 힙 메모리 (0) | 2026.03.29 |