C++ 구조체란?
구조체(structure)는 서로 다른 데이터 타입을 가진 항목들을 하나로 묶은 사용자 정의 자료형입니다. 여러 종류의 데이터 레코드를 포함하는 복잡한 데이터 구조를 만들어야 할 때 매우 유용하며, struct 키워드를 사용하여 정의합니다.
구조체의 기본적인 예시는 다음과 같습니다.
struct employee {
int empID;
char name[50];
float salary;
};위 구조체는 직원의 ID(int), 이름(char 배열), 급여(float)처럼 서로 다른 타입의 멤버 변수들을 하나의 단위로 관리할 수 있게 해줍니다.
구조체로 정보 저장 및 출력하기
다음은 구조체를 사용하여 직원 정보를 저장하고 화면에 출력하는 C++ 프로그램의 전체 코드입니다.
예제
#include <iostream>
using namespace std;
struct employee {
int empID;
char name[50];
int salary;
char department[50];
};
int main() {
struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } };
cout<<"The employee information is given as follows:"<<endl;
cout<<endl;
for(int i=0; i<3;i++) {
cout<<"Employee ID: "<<emp[i].empID<<endl;
cout<<"Name: "<<emp[i].name<<endl;
cout<<"Salary: "<<emp[i].salary<<endl;
cout<<"Department: "<<emp[i].department<<endl;
cout<<endl;
}
return 0;
}실행 결과
The employee information is given as follows: Employee ID: 1 Name: Harry Salary: 20000 Department: Finance Employee ID: 2 Name: Sally Salary: 50000 Department: HR Employee ID: 3 Name: John Salary: 15000 Department: Technical
코드 상세 설명
1. 구조체 정의
위 프로그램에서 구조체는 main() 함수보다 먼저 정의됩니다. 이 구조체는 직원의 ID, 이름, 급여, 부서 정보를 멤버 변수로 포함하고 있습니다.
struct employee {
int empID;
char name[50];
int salary;
char department[50];
};2. 구조체 배열 초기화
main() 함수 안에서는 struct employee 타입의 객체 배열이 선언되며, 각 요소에는 직원 ID, 이름, 급여, 부서 값이 순서대로 저장됩니다.
struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } };3. 반복문으로 출력하기
저장된 구조체 값들은 for 반복문을 통해 순차적으로 화면에 출력됩니다. 각 반복마다 멤버 접근 연산자(.)를 사용해 배열의 i번째 직원 정보를 읽어와 출력합니다.
cout<<"The employee information is given as follows:"<<endl;
cout<<endl;
for(int i=0; i<3;i++) {
cout<<"Employee ID: "<<emp[i].empID<<endl;
cout<<"Name: "<<emp[i].name<<endl;
cout<<"Salary: "<<emp[i].salary<<endl;
cout<<"Department: "<<emp[i].department<<endl;
cout<<endl;
}마무리
이처럼 C++의 구조체를 활용하면 서로 다른 데이터 타입의 정보를 하나의 단위로 묶어 체계적으로 관리할 수 있습니다. 실무에서는 구조체를 배열과 함께 사용해 대량의 레코드 데이터를 효율적으로 처리할 수 있으며, 이러한 개념은 이후 배우게 될 클래스(class)와 객체 지향 프로그래밍의 기초가 됩니다.