구조체(Struct) 란?
: 여러 개의 다양한 타입의 데이터를 하나로 묶어서 관리할 수 있는 사용자 정의 데이터 타입
- C++에서 구조체는 객체지향 프로그래밍에서 클래스와 비슷한 역할을 하지만, 기본적으로 멤버 함수가 없는 데이터 구조체
- 구조체는 주로 여러 데이터를 하나의 단위로 묶어야 할 때 사용
- array는 한 가지 데이터 타입만 사용할 수 있으므로, 이를 보완!
장점
- 데이터 구조화
- 모듈화
- 재사용성
구조체 정의
#include <iostream>
using namespace std;
// 구조체 정의
struct Person {
string name; // 이름
int age; // 나이
double height; // 키
};
int main() {
// 구조체 변수 선언
Person person1;
// 구조체 멤버에 값 할당
person1.name = "Alice";
person1.age = 30;
person1.height = 5.5;
// 구조체 멤버에 접근하여 출력
cout << "Name: " << person1.name << endl;
cout << "Age: " << person1.age << endl;
cout << "Height: " << person1.height << " feet" << endl;
return 0;
}
출력 예시:
Name: Alice
Age: 30
Height: 5.5 feet
구조체 사용법
- 구조체 멤버 접근
- 구조체의 멤버에는 점(.) 연산자를 사용하여 접근할 수 있습니다.
- 예: person1.name, person1.age
- 구조체 변수 선언
- 구조체를 정의한 후, 해당 구조체를 사용할 변수를 선언할 수 있습니다.
- 예: Person person1;
- 구조체 초기화
- 구조체 멤버에 값을 할당할 때는 점 연산자 또는 구조체 초기화 목록을 사용할 수 있습니다.
초기화 방법1: 점 연산자 사용
person1.name = "Bob";
person1.age = 25;
person1.height = 5.8;
초기화 방법2: 구조체 초기화 목록 사용
Person person2 = {"Charlie", 28, 6.0}; // 초기화 목록 사용
구조체 특징
- 다양한 데이터 타입의 멤버를 포함: 구조체는 다양한 데이터 타입을 멤버로 가질 수 있어, 여러 개의 관련 데이터를 하나의 단위로 묶을 수 있습니다.
- 값에 의한 복사: 구조체는 기본적으로 값에 의한 복사가 이루어지며, 구조체를 다른 변수에 할당하면 그 값이 복사됩니다.
- 구조체와 클래스의 차이: C++에서는 struct와 class가 거의 동일합니다. 다만, 구조체는 기본적으로 public 접근 제한자를 사용하고, 클래스는 기본적으로 private 접근 제한자를 사용합니다.
구조체 예시: 학생 정보를 저장하는 프로그램
#include <iostream>
#include <vector>
using namespace std;
// 학생 정보를 저장하는 구조체 정의
struct Student {
string name;
int age;
string student_id;
};
int main() {
// 여러 학생 정보를 저장하는 벡터 생성
vector<Student> students = {
{"Alice", 20, "S001"},
{"Bob", 21, "S002"},
{"Charlie", 22, "S003"}
};
// 모든 학생의 정보를 출력
for (const auto& student : students) {
cout << "Name: " << student.name << ", Age: " << student.age
<< ", ID: " << student.student_id << endl;
}
return 0;
}
출력예시:
Name: Alice, Age: 20, ID: S001
Name: Bob, Age: 21, ID: S002
Name: Charlie, Age: 22, ID: S003
구조체 내 함수 사용
- C++에서는 구조체 내에 함수도 포함할 수 있다.
#include <iostream>
using namespace std;
// 구조체 정의
struct Circle {
double radius;
// 면적을 계산하는 함수
double area() const {
return 3.14159 * radius * radius;
}
};
int main() {
// Circle 구조체 변수 생성 및 초기화
Circle c1 = {5.0};
// 구조체 멤버 함수 호출
cout << "Area of circle: " << c1.area() << endl;
return 0;
}
출력 예시:
Area of circle: 78.5398
구조체 포인터와 참조
#include <iostream>
using namespace std;
struct Person {
string name;
int age;
};
int main() {
Person p1 = {"Alice", 30};
Person* p2 = &p1; // 구조체 포인터
cout << "Name: " << p2->name << ", Age: " << p2->age << endl;
return 0;
}
- p2->name처럼 화살표 연산자(->)를 사용해, 포인터로 구조체 멤버에 접근할 수 있다.
#include <bits/stdc++.h>
using namespace std;
// typedef
struct Node{
// 구조체 멤버 변수에 값 초기화 불가능
int a;
char b;
int arr[3];
};
typedef struct Node2{
int a7;
int b7;
}Node2;
Node abc(int n, char m, struct Node s){
return s;
}
int main(void)
{
int a1;
Node t; // 구조체 변수
t.a = 3;
t.b = 'A';
Node k = {4, 'B'}; // 변수 선언시 값 초기화 가능
Node2 test = {.b7 = 70}; // 지정 초기화
int tt = 100;
char tt2 = 'A';
Node ret = abc(tt, tt2, (struct Node){3, 'T'});
return 0;
}
#include <bits/stdc++.h>
using namespace std;
// typedef
struct Node{
// 구조체 멤버 변수에 값 초기화 불가능
int a;
char b;
int arr[3];
};
typedef struct Node2{
int a7;
int b7;
}Node2;
Node abc(int n, char m, struct Node s){
return s;
}
int main(void)
{
int a1;
Node t; // 구조체 변수
t.a = 3;
t.b = 'A';
Node k = {4, 'B'}; // 변수 선언시 값 초기화 가능
Node2 test = {.b7 = 70}; // 지정 초기화
int tt = 100;
char tt2 = 'A';
Node ret = abc(tt, tt2, (struct Node){3, 'T'});
return 0;
}
'IVS > C 프로그래밍' 카테고리의 다른 글
[C++] 공백있는 문자열 입력받기 - getline (2) | 2025.01.09 |
---|---|
[C++] 중첩 반복문 - continue, break (0) | 2025.01.08 |
[C++] 포인터 (0) | 2025.01.08 |
[C++] Vector 정렬하기 - lambda로 비교함수 재정의 (0) | 2025.01.07 |
[C++] scanf로 char형 입력받기 (1) | 2025.01.07 |