(C++)04.4 복합 데이터 유형 – 구조

– 관련 정보를 그룹화하여 하나의 단위로 저장할 수 있습니다.

– C++에서 구조체는 객체지향 프로그래밍의 핵심인 ‘클래스’의 기반이다.

– 사용자 정의 데이터 유형

struct inflatable // 구조체 선언
{
	char name(20);
    float volume;
    double price;
};

// structur.cpp -- 간단한 구조체
#include <iostream>
struct inflatable       // 구조체 선언
{
    char name(20);
    float volume;
    double price;
};

int main()
{
    using namespace std;
    inflatable guest =
    {
        "Glorious Gloria",  // name value
        1.88,               // volume value
        29.99               // price value
    };                      // guest는 inflatable형의 구조체 변수

                            // 지정된 값으로 초기화됨
    inflatable pal = 
    {
        "Audacios Arther",
        3.12,
        32.99
    };                      // pal은 inflatable형의 두번째 수이다.
// 참고 : 어떤 C++ 시스템에서는 다음과 같은 형식을 요구한다.
// static inflatable guest = 
    
    cout << "The model ballons we're selling now are\n" << guest.name;
    cout << " and " << pal.name << ".\n";
// pal.name은 pal 변수의 name 멤버이다.
    cout << "I'll give you both product for $";
    cout << guest.price + pal.price << "!\n";
    return 0;
}

// The model ballons we're selling now are
// Glorious Gloria and Audacios Arther.
// I'll give you both product for $62.98!

구조체를 선언하는 방법에는 두 가지가 있습니다.

첫 번째는 main() 함수 내에서 여는 중괄호 바로 뒤에 선언을 배치하는 것입니다.

두 번째는 선언을 main() 함수 앞에 두는 것입니다.

이 예제를 내부 또는 외부에 배치하는 것은 중요하지 않지만 다기능 프로그램에서는 큰 차이를 만들 수 있습니다.

외부 선언은 선언 후 모든 함수에 사용할 수 있지만

내부 선언은 선언이 포함된 함수에서만 사용할 수 있습니다.

  • 구조의 다른 속성
// assgn_st.cpp -- 구조체 대입
#include <iostream>
struct inflatable
{
    char name(20);
    float volume;
    double price;
};
int main()
{
    using namespace std;
    inflatable bouquet =
    {
        "sunflowers",
        0.20,
        12.49
    };
    inflatable choice;
    cout << "bouquet: " << bouquet.name << " for $";
    cout << bouquet.price << endl;

    choice = bouquet;       // 한 구조체를 다른 구조체에 대입
    cout << "choice: " << choice.name << " for $";
    cout << choice.price << endl;
    return 0;
}

// bouquet: sunflowers for $12.49
// choice: sunflowers for $12.49

구조체 선언 직후에 변수 이름을 선언할 수도 있지만, 이는 혼동하기 쉽습니다.

  • 구조의 배열
inflatable gifts(100); // inflatable형 구조체 100개의 배열

cin >> gifts(0).volume;		// 첫번째 구조체의 volume 멤버에 입력
cout << gifts(99).price << endl; // 마지막 구조체의 price 멤버를 출력

선물 자체는 구조체가 아니라 배열이기 때문에 gifts.price와 같은 표현은 의미가 없습니다.

// arrstruc.cpp -- 구조체의 배열
#include <iostream>
struct inflatable
{
    char name(20);
    float volume;
    double price;
};
int main()
{
    using namespace std;
    inflatable guests(2) =          // 구조체 배열 초기화
    {
        {"Bambi", 0.5, 21.99},      // 배열에 있는 첫 번째 구조체
        {"Godzilla", 2000, 565.99}  // 배열에 있는 그 다음 구조체
    };
    
    cout << "The combinded volume of " << guests(0).name << " and " << guests(1).name
        << " is\n"
        << guests(0).volume + guests(1).volume
        << " cubic feet.\n";
        return 0;
}

// The combinded volume of Bambi and Godzilla is
// 2000.5 cubic feet.