본문 바로가기
프로그래밍언어/C++

struct(구조체)

by Slow Motion~ 2023. 2. 20.
728x90

일반적인 선언과 struct로 선언했을때의 장점은 무엇일까 싶어 예시를 만들어 보았다.

 

구조체는 서로 관련된 변수를 하나의 그룹으로 묶어 관리할 수 있는 데이터 타입이다.

 

다양한 변수를 그룹을 묶어 관리할 수 있는 데이터 타입니다.

 

장점은 가독성도 좋고 유지보수하기 좋다.

 

그러니까 묶어서 사용할때 좋다.

#include <iostream>
#include <string>
using namespace std;

// 구조체를 사용하여 학생 정보를 저장하는 예시
struct Student {
    string name;
    int age;
    string major;
};

// 학생 정보를 출력하는 함수
void printStudentInfo(Student s) {
    cout << "Name: " << s.name << endl;
    cout << "Age: " << s.age << endl;
    cout << "Major: " << s.major << endl;
}

int main() {
    // 단순 선언으로 학생 정보를 저장하는 경우
    string name = "John";
    int age = 20;
    string major = "Computer Science";

    // 학생 정보를 출력하는 함수 호출
    cout << "Student Info:" << endl;
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Major: " << major << endl;

    // 구조체를 사용하여 학생 정보를 저장하는 경우
    Student s;
    s.name = "Jane";
    s.age = 21;
    s.major = "Mathematics";

    // 학생 정보를 출력하는 함수 호출
    cout << "Student Info:" << endl;
    printStudentInfo(s);

    return 0;
}

댓글