12.7 Non-static member initialization

주홍영·2022년 3월 17일
0

Learncpp.com

목록 보기
131/199

https://www.learncpp.com/cpp-tutorial/non-static-member-initialization/

우리는 non-static한 member init을 할 수 있다

#include <iostream>

class Rectangle
{
private:
    double m_length{ 1.0 };
    double m_width{ 1.0 };

public:

    Rectangle(double length, double width)
        : m_length{ length },
          m_width{ width }
    {
        // m_length and m_width are initialized by the constructor (the default values aren't used)
    }

    Rectangle(double length)
        : m_length{ length }
    {
        // m_length is initialized by the constructor.
        // m_width's default value (1.0) is used.
    }

    void print()
    {
        std::cout << "length: " << m_length << ", width: " << m_width << '\n';
    }

};

int main()
{
    Rectangle x{ 2.0, 3.0 };
    x.print();

    Rectangle y{ 4.0 };
    y.print();

    return 0;
}

위의 코드를 보면 member variable 선언과 동시에 {1.0}으로 init을 하고 있는 것을 알 수 있다
만약 initalizer list로 해당 member variable을 초기화 하지 않는 다면
default 값이 그대로 초기화에 사용될 것임을 암시한다
따라서 위의 코드의 출력은 다음과 같다

length: 2.0, width: 3.0
length: 4.0, width: 1.0

참고로 non-static member initialization의 초기화 방법은 다음과 같다

class A
{
    int m_a = 1;  // ok (copy initialization)
    int m_b{ 2 }; // ok (brace initialization)
    int m_c(3);   // doesn't work (parenthesis initialization)
};

() 괄호 초기화는 지원하지 않는다

profile
청룡동거주민

0개의 댓글