본문 바로가기
C++/C++ 기초 문법

[C++] 구조체

by 후야- 2023. 12. 23.

1. 구조체

-> 구조체는 기존에 정의된 타입을 한 개 이상 묶어서 새로운 타입으로 정의할 수 있다.

-> 구조체의 대표적인 예로 데이터베이스 레코드가 있다.

-> 구조체 사용하려면 선언을 해야한다. (struct) 

 

 main.cpp

#include <iostream>
#include <format>

using namespace std;

struct Student    // 구조체 선언
{
	int num;         // int 에 저장
	double grade;    // double 에 저장
};

int main()
{
	Student s1;      // Student >> s1 에 집어넣기
	s1.num = 211;    // s1 의 num 멤버에 211 저장
	s1.grade = 2.7;  // s1 의 grade 멤버에 2.7 저장

	cout << format("학번 : {}", s1.num) << endl;
	cout << format("학점 : {}", s1.grade) << endl;

	return 0;
}

 

 

 main.cpp

#include <iostream>
#include <format>

using namespace std;

struct Student    // 구조체 선언
{
	int num;         // int 에 저장
	double grade;    // double 에 저장
};

int main()
{
	Student s1, s2;      // Student >> s1, s2 생성하기
	s1.num = 211;    // s1 의 num 멤버에 211 저장
	s1.grade = 2.7;  // s1 의 grade 멤버에 2.7 저장
	s2.num = 53;
	s2.grade = 3.5;

	cout << format("학번 : {}번", s1.num) << endl;
	cout << format("학점 : {}", s1.grade) << endl;
	cout << format("학번 : {}번", s2.num) << endl;
	cout << format("학점 : {}", s2.grade) << endl;

	return 0;
}

 

-> 이런식으로 사용이 가능하다.


2. 모듈 인터페이스 파일 사용

◾ employee.ixx

export module employee;

export struct Employee
{
	char firstName;
	char latsName;
	int number;
	int salary;
};

 

main.cpp

#include <iostream>
#include <format>

import employee;

using namespace std;

int main()
{
	// 직원 레코드 생성 및 값 채우기
	Employee anEmployee;
	anEmployee.firstName = 'B';
	anEmployee.latsName = 'H';
	anEmployee.number = '79';
	anEmployee.salary = 50000;

	// 직원 레코드에 저장된 값 출력하기
	cout << format("직원 : {} {}", anEmployee.firstName, anEmployee.latsName) << endl;
	cout << format("번호 : {}", anEmployee.number) << endl;
	cout << format("월급 : {}", anEmployee.salary) << endl;

	return 0;
}

 

-> 모듈에 있는 타입을 익스포트하려면 그 대상앞에 export 키워드를 붙여줘야 한다.

-> Employee 타입으로 선언한 변수는 이 구조체에 있는 모든 필드를 가진다.

-> 구조체를 구성하는 각 필드는 도트(.) 연산자를 사용해서 접근한다.

연산자 (.) 을 사용하면 나열된다.

 

 

✳ 모듈을 사용하려고 시간을 엄청 뺏겼다. 속성 페이지에 가서 C++ 언어 표준을 최신 버전으로 바꿔야한다.

 

 

 

 

 

'C++ > C++ 기초 문법' 카테고리의 다른 글

[C++] 조건 연산자(?:) -> 삼항 연산자  (0) 2023.12.26
[C++] 조건문 if , switch 문  (0) 2023.12.23
[C++] 열거 타입  (0) 2023.12.22
[C++] 인라인(inline) 함수  (0) 2023.12.22
[C++] 매개변수의 디폴트 값  (0) 2023.12.21