9.18 Struct aggregate initialization

주홍영·2022년 3월 14일
0

Learncpp.com

목록 보기
109/199

Aggregate initialization of a struct

struct Employee
{
    int id {};
    int age {};
    double wage {};
};

int main()
{
    Employee frank = { 1, 32, 60000.0 }; // copy-list initialization using braced list
    Employee robert ( 3, 45, 62500.0 );  // direct initialization using parenthesized list (C++20)
    Employee joe { 2, 28, 45000.0 };     // list initialization using braced list (preferred)

    return 0;
}

위와 같은 style로 initialization을 할 수 있다

Missing initializers in an initializer list

struct Employee
{
    int id {};
    int age {};
    double wage {};
};

int main()
{
    Employee joe { 2, 28 }; // joe.wage will be value-initialized to 0.0

    return 0;
}

위와 같은 경우 wage가 0.0으로 초기화 된다고 한다

Employee joe {}; // value-initialize all members

위와 같이 init하면 모든 member가 0으로 초기화된다

Const structs

struct Rectangle
{
    double length {};
    double width {};
};

int main()
{
    const Rectangle unit { 1.0, 1.0 };
    const Rectangle zero { }; // value-initialize all members

    return 0;
}

const로 struct type variable을 instantiate 할 수 있다
이때는 필수적으롤 initialization이 되어야 한다

Designated initializers (c++ 20)

앞서 말했든 initialization을 할 때 member의 순서대로 init 할 수 있었다

struct Foo
{
    int a {};
    int c {};
}

int main()
{
    Foo f { 1, 3 }; // f.a = 1, f.c = 3
}

그리고 만약 생략되는 경우 rightmost부터 0으로 초기화된다

struct Foo
{
    int a {};
    int b {}; // just added
    int c {};
};

int main()
{
    Foo f { 1, 3 }; // now, f.a = 1, f.b = 3, f.c = 0
}

하지만 c++20에서 명시적으로 초기화 할 수 있는 방법을 지원한다

struct Foo
{
    int a{ };
    int b{ };
    int c{ };
};

int main()
{
    Foo f1{ .a{ 1 }, .c{ 3 } }; // ok: f.a = 1, f.b = 0 (value initialized), f.c = 3
    Foo f2{ .b{ 2 }, .a{ 1 } }; // error: initialization order does not match order of declaration in struct

    return 0;
}

첫번째 사례를 보면 a와 c를 초기화 할 수 있다
하지만 두번째 사례에서 member 순서를 치키지 않아서 error가 발생했다

Assignment with an initializer list

만약 stuct type 의 member를 모두 변화시키고 싶은게 아닌 일부만 수정하고 싶은 경우에
다음과 같은 방법을 사용한다

struct Employee
{
    int id {};
    int age {};
    double wage {};
};

int main()
{
    Employee joe { 1, 32, 60000.0 };
    joe = { joe.id, 33, 66000.0 }; // Joe had a birthday and got a raise

    return 0;
}

joe.id는 변화를 원치 않았기에 다시 joe.id를 initializer로 넘겨주어 사용했다

단어장

aggregate : 골재
detour : 우회
However, before we show you how to initialize a struct, let’s take a short detour.

profile
청룡동거주민

0개의 댓글