https://www.youtube.com/watch?v=r7Y2aKV5muw&list=PLgqG2uj21HgkcfVtlr5rPekQl5VWJEnIB&index=10

학습 목표

  1. 구조체란
  2. 구조체의 선언과 초기화
  3. 구조체 배열

구조체란

c++의 장점 중 하나인 사용자의 입맛대로 원하는 데이터형을 만들어 사용하는 특징이 잘나타는 복합체가 바로 구조체이다.

구조체와 배열의 차이점은 배열은 같은 데이터형의 집합이라면 구조체는 다른 데이터형이 허용되는 데이터의 집합이다.

구조체의 선언과 초기화

아래의 방식처럼 구조체를 선언을 할 수 있다.

#include <iostream>

using namespace std;
int main(){
    struct Mysttuct
    {
        string name;
        string position;
        float height;
        float weight;
    };
    
    Mysttuct A = {
        "Son",
        "Striker",
        183,
        77
    };

    cout << A.name << endl;
    cout << A.position << endl;
    cout << A.height << endl;
    cout << A.weight << endl;

    
}

또 다른 방식은 구조체 뒤에 선언을 통해서도 만들 수 있다. 아무런 값을 넣지 않으면 0으로 초기화 할 수 있다.

#include <iostream>

using namespace std;
int main(){
    struct Mysttuct
    {
        string name;
        string position;
        float height;
        float weight;
    } B;
    
    B={

    };
    cout << B.height << endl;
    
}

구조체 배열

구조체 역시 배열로 선언을 할 수 있다. 출력도 배열로 접근하여 출력해야한다.

#include <iostream>

using namespace std;
int main(){
    struct Mysttuct
    {
        string name;
        string position;
        float height;
        float weight;
    };
    
    Mysttuct A[2] = {
        {"A", "A", 1, 1},
        {"B", "B", 2, 2}
    };
    cout << A[0].height << endl;
    
}