Study/C++

[C++]04.4 복합데이터형 - 구조체

SigmoidFunction 2023. 3. 17. 10:39
728x90

- 관련된 정보를 하나의 단위로 묶어서 저장할 수 있다.

- 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!

구조체 선언에는 2가지 방법이 있다.

 

첫번째는 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자체는 구조체가 아니라 배열이므로 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.
728x90