ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 생성자 초기화, explicit
    C++/Common 2023. 10. 5. 00:02

    생성자 관련해서 다른언어와 거의 같았다면 흘려보고 말생각 이었는데 생각보다 C++는 문법적으로 제 생각보다 더 다양한 부분이 있어서 오늘도 정리하게 되었습니다.

    생성자 초기화 주의사항

    #include <iostream>
    using namespace std;
    
    class Position 
    {
    public:
        Position() : _x(10), _y(10)
        {
            Print();
        }
    
        Position(int n) : _x(n),_y(n)
        {
            Print();
        }
    
    
        void Print()
        {
            cout << _x << ", " << _y << endl;
        }
    public :
        int _x;
        int _y;
    };
    
    class Player
    {
    public :
        Player() 
        {
            position = Position(20);
        }
    
    
    public :
        Position position;
    };
    
    int main()
    {
        Player p;
    }
    

    출력결과는
    10,10
    20,20
    이렇게 두번이 나오게 됩니다.

    할당 순서를 생각하면 알수있는데 먼저 멤버인 position은 기본 생성자인 10,10으로 생성됩니다.

    Player() 
    {
        position = Position(20);
    }

    그뒤에 Position(20)을 추가로 해준 것이 됩니다. 이런 현상을 막으려면 생성자 스코프 내에서 할당보다는 다음과같이

    Player() : position(20)
    {
    
    }

    초기화 코드를 넣어주는게 이중할당을 막을 수 있습니다.

    explicit

    class Position 
    {
    public:
        Position() : _x(10), _y(10)
        {
            Print();
        }
    
        Position(int n) : _x(n),_y(n)
        {
            Print();
        }
    
        void operator=(int n)
        {
            _x = n;
            _y = n;
        }
    
        void Print()
        {
            cout << _x << ", " << _y << endl;
        }
    
    
    public :
        int _x;
        int _y;
    };
    
    int main()
    {
        Position x = 30;
    }

    위와같은 구문이 있을때 Position x = 30;은
    초기 기본 할당후 연산자 오버로딩으로 동작된 것일까요?
    아니면 생성자 Position(int n)으로 동작된 것일까요?

    정답은 생성자 Position(int n)으로 동작됩니다.
    정말 까딱하면 개발자의 의도와 다른 명령이 실행될수 있을것 같다는 생각이 듭니다.
    그래서 이것을 막기위해서

    explicit Position(int n) : _x(n),_y(n)
    {
        Print();
    }

    파라메터를 하나만 받는 생성자에는 explicit을 넣어주면
    초기 할당에서 Position x = 30;와 같은 구문을 사용할 수 없도록 컴파일에러가 발생하게 됩니다.
    Position x= Position(30); 으로 명확히 해주면 정상적으로 컴파일 됩니다.

    'C++ > Common' 카테고리의 다른 글

    C++ 포인터와 레퍼런스  (2) 2023.10.03
Designed by Tistory.