본문 바로가기

IT 관련자료/C++

생성자맴버 초기화

 

#include <iostream>
#include <string>

using namespace std;

class B
{
public:
    int _b;

public:
    B(const int& _b_in)
        :_b(_b_in)
    {
    }
    int return_b(const B &one)
    {
        return one._b;
    }

};



class Something
{
private:
    //여기서 초기화를 해줘도 아래에 있는 생성자가 우선이다.
    int _i = 10;
    double _d = 10.1;
    char _c = 'f';
    int _arr[5]{ 1,2,3,4,5 };

    B _b;
    

public:
    Something()
        //생성자 초기화목록
        : _i(1), _d(3.14), _c('a'), _arr{ 1,2,3,4,5 }, _b(_i - 1)
    {
        //이거 빈칸은 왜두는지 모르겠네... >> 여기서 초기화 하면서 수행할 기능 정의할 수 있음
        // 예를들어 cout << this << endl; 하면 해당 생성자 주소 출력
    }
    void print()
    {
        //여기서 _b를 불러올 수 없는이유를 모르겠네 >> _b._b 이렇게 불러야함
        cout << _i << " " << _d << " " << _c <<  _b._b<< endl;
        for (auto& e : _arr)
            cout << e << " ";
        cout << endl;

    }
};



int main()
{
    Something som;
    som.print();



    return 0;
}

'IT 관련자료 > C++' 카테고리의 다른 글

위임생성자  (0) 2022.02.24
객체지향 기본개념 정리코드  (0) 2022.02.24
객체지향 프로그래밍의 기초  (0) 2022.02.22
단언하기(Assert)  (0) 2022.02.22
방어적 프로그래밍의 개념  (0) 2022.02.21