작은 걸음 V — 나만의 자료형 만들기
관련된 값 묶기
관련된 값 묶기
이번에 배울 것
struct는 관련된 값들을 묶는 새 타입을 정의합니다. Player 하나에 이름과 점수를 함께 담아 봅니다.
실행해 보기
예제 · example1.cpp
struct Player
{
String name;
int score;
};
void small_main()
{
Player player;
player.name = "Alex";
player.score = 1200;
print(player.name, ": ", player.score);
}
String과 int가 이미 있던 타입이라면 Player는 우리가 만든 타입입니다. player.name처럼 점으로 안의 값에 접근합니다.
예제는 Alex: 1200을 출력합니다. struct 정의의 닫는 중괄호 뒤에는 ;이 필요합니다.
Exercise — Point 만들기
x와 y를 double로 가지는 Point struct를 만들고 (3.5, 7.0)을 저장해 출력하세요.
연습 문제 코드 · exercise1_starter.cpp
struct Point
{
// Add x and y here.
double x;
double y;
};
void small_main()
{
Point point;
point.x = 3.5;
point.y = 7.0;
print(point.x, ", ", point.y);
}
Hint
struct Point { double x; double y; };로 시작하세요.
풀이 보기
struct Point
{
double x;
double y;
};
void small_main()
{
Point point;
point.x = 3.5;
point.y = 7.0;
print(point.x, ", ", point.y);
}